手撕Promise.any
Promise.any()
接收一个Promise
可迭代对象,只要其中的一个promise
成功,就返回那个已经成功的promise
。如果可迭代对象中没有一个promise
成功(即所有的promises
都失败/拒绝),就返回一个失败的promise
和AggregateError
类型的实例,它是Error
的一个子类,用于把单一的错误集合在一起。本质上,这个方法和Promise.all()
是相反的。
Promise.any = function (promises) { return new Promise((resolve, reject) => { const length = promises.length; let rejectCount = 0; promises.forEach((promise) => { Promise.resolve(promise).then(value => { resolve(value) }, () => { rejectCount++ if (rejectCount === length) { reject('AggregateError:All promises were rejected') } }) }) }) } const pErr1 = new Promise((resolve, reject) => { reject('总是失败1'); }); const pErr2 = new Promise((resolve, reject) => { reject('总是失败2'); }); Promise.any([pErr1, pErr2]).catch((err) => { console.log(err); }) const pErr3 = new Promise((_, reject) => { reject("总是失败3"); }); const pErr4 = new Promise((_, reject) => { reject("总是失败4"); }); const pSlow1 = new Promise((resolve, _) => { setTimeout(resolve, 600, "第二个完成"); }); const pSlow2 = new Promise((resolve, _) => { setTimeout(resolve, 500, "第一个完成"); }); const pFast = new Promise((resolve, _) => { setTimeout(resolve, 1000, "最后完成"); }); Promise.any([pErr3, pErr4, pSlow2, pSlow1, pFast]).then((value) => { console.log(value); })