由于Promise的链式回调实在太难,先尝试 Promise.all 的写法
需求分析
- 接收一个 Promise 数组作为参数
- 全部 Promise resolve 则返回 结果数组
- 任意一个 Promise reject 则:有 catch 捕获,无 catch 直接抛出错误
- 返回一个 thenable 的Promise
- 如果传入的参数非 Promise 则直接返回值
先看下正常的Promise的返回(也作为测试代码)
Promise.all([
new Promise((resolve) => {
resolve(1)
}),
new Promise((resolve) => {
resolve(2)
})
]).then(res => {
console.log('res', res)
})
Promise.all([
new Promise((resolve, reject) => {
reject(1)
}),
new Promise((resolve) => {
resolve(2)
})
]).then(res => {
console.log('res', res)
})
Promise.all([
new Promise((resolve, reject) => {
reject(1)
}),
new Promise((resolve) => {
resolve(2)
})
]).then(res => {
console.log('res', res)
}).catch(error => {
console.log('error')
})
代码
const promiseAll = (pArr) => {
let count = 0
let res = []
return new Promise((resolve, reject) => {
pArr.forEach((item, index) => {
if (item instanceof Promise) {
item.then(data => {
res[index] = data
++count
if (count === pArr.length) {
resolve(res)
}
}, reject)
} else {
res[index] = item
++count
}
})
})
}
测试
promiseAll([
new Promise((resolve) => {
setTimeout(() => {
resolve(1)
}, 3000)
}),
new Promise((resolve) => {
resolve(2)
})
]).then(res => {
console.log('res', res)
})
promiseAll([
new Promise((resolve, reject) => {
reject(1)
}),
new Promise((resolve) => {
resolve(2)
})
]).then(res => {
console.log('res', res)
}).catch(e => {
console.log('处理reject', e)
})
promiseAll([
1,
new Promise((resolve, reject) => {
setTimeout(() => {
reject(1)
}, 3000)
}),
2,
new Promise((resolve) => {
resolve(2)
}),
3,
]).then(res => {
console.log('res', res)
}).catch(error => {
console.log('error')
})