手写Promise,A+规范
2020-05-28 本文已影响0人
littleyu
https://github.com/zch233/myPromise
再写一个 Promise.allSettled
(返回所有的promise结果,不论成功或失败。新出的api,兼容性不太好)
const task1 = () => Promise.reject(1111)
const task2 = () => Promise.reject(2222)
const task3 = () => Promise.resolve(3333)
原版用法:
第一步,解决 Promise.all
其中一个失败就返回的问题
// 既然失败就会返回,我们干脆直接让所有的 Promise 都成功就好了
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 数组
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))
运行:
最后一步
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。