https://github.com/zch233/myPromise
再写一个 Promise.allSettled
(返回所有的promise结果,不论成功或失败。新出的api,兼容性不太好)
1 2 3
| const task1 = () => Promise.reject(1111) const task2 = () => Promise.reject(2222) const task3 = () => Promise.resolve(3333)
|
原版用法:
第一步,解决 Promise.all
其中一个失败就返回的问题
1 2 3 4 5 6
| const x = promise => promise.then(data => ({ status: 'ok', data }), data => ({ status: 'not ok', data })) const task1 = () => Promise.reject(1111) const task2 = () => Promise.reject(2222) const task3 = () => Promise.resolve(3333) Promise.all([x(task1()), x(task2()), x(task3())]).then(data => console.log(data))
|
运行:
已经得到和 Promise.settled
一样的结果了,接下来我们再优化一下代码
辅助函数 x 接受一个 promise 数组
1 2 3 4 5 6 7
| const x = promiseList => promiseList.map(promise => promise.then(data => ({ status: 'ok', data }), data => ({ status: 'not ok', data }))) // 对比上一步的 x // const x = promise => promise.then(data => ({ status: 'ok', data }), data => ({ status: 'not ok', data })) const task1 = () => Promise.reject(1111) const task2 = () => Promise.reject(2222) const task3 = () => Promise.resolve(3333) Promise.all(x([task1(), task2(), task3()])).then(data => console.log(data))
|
运行:
最后一步
1 2 3 4 5 6
| const x = promiseList => promiseList.map(promise => promise.then(data => ({ status: 'ok', data }), data => ({ status: 'not ok', data }))) Promise.settled2 = promiseList => Promise.all(x(promiseList)) const task1 = () => Promise.reject(1111) const task2 = () => Promise.reject(2222) const task3 = () => Promise.resolve(3333) Promise.settled2([task1(), task2(), task3()]).then(data => console.log(data))
|
运行:
end。