var arr=[1,2,3,4,5,6,7,8,9]
function PromiseForEach(arr, cb) {
let realResult = []
let result = Promise.resolve()
arr.forEach((a, index) => {
result = result.then(() => {
return cb(a).then((res) => {
realResult.push(res)
})
})
})
return result.then(() => {
return realResult
})
}
PromiseForEach(arr, (ele) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(ele);
return resolve(ele);
}, Math.random()*1000);
})
}).then((data) => {
console.log("成功");
console.log(data);
}).catch((err) => {
console.log("失败");
console.log(err)
});
网友评论