Promise.all的实现
const p1 = new Promise((resolve,reject) => {
setTimeout(() => {
resolve({data: { name: 'p1'}})
},10)
// 异常情况reject('异常原因')
})
const p2 = new Promise((resolve,reject) => {
setTimeout(() => {
resolve({data: { name: 'p2'}})
},30)
// 异常情况reject('异常原因')
})
const Promise_all = function(promiseArr) {
return new Promise((resolve,reject) => {
let result = []
if (Array.isArray(promiseArr) && promiseArr.length) {
promiseArr.forEach(promise => {
promise.then(res => {
result.push(res)
// 确保所有promise都是完成状态,然后返回
if(result.length === promiseArr.length) {
console.log(result)
resolve(result)
}
},(err) => {
reject(err)
})
});
} else {
reject('参数必须是数组')
}
})
}
Promise_all([p1,p2]).then(resArr => {
console.log(resArr)
}, err => {
console.log(err)
})
/*
* (2) [{…}, {…}]
* 0: data: {name: "p1"}
* 1: data: {name: "p2"}
*/
Promise.race的实现
const p1 = new Promise((resolve,reject) => {
setTimeout(() => {
resolve({data: { name: 'p1'}})
},30)
// 异常情况reject('异常原因')
})
const p2 = new Promise((resolve,reject) => {
setTimeout(() => {
resolve({data: { name: 'p2'}})
},10)
// 异常情况reject('异常原因')
})
const Promise_race = function(promiseArr) {
return new Promise((resolve,reject) => {
if (Array.isArray(promiseArr) && promiseArr.length) {
promiseArr.forEach(promise => {
promise.then(res => {
resolve(res)
},(err) => {
reject(err)
})
});
} else {
reject('参数必须是数组')
}
})
}
Promise_race([p1,p2]).then(resArr => {
console.log(resArr)
}, err => {
console.log(err)
})
/*
* {data: {name: "p2"}}
*/