需求是有一个objects数组,其中的元素是每次异步事件需要的参数
异步事件事件接受参数并且串行执行,最终返回一个promise结果
Promise.all似乎是并行的?
const PromiseForEach = (objects, asyncDosometing) => {
return new Promise((resolve, reject) => {
Promise.all(objects.map((obj) => {
return new Promise((resolve, reject) => {
return asyncDosometing(obj).then(resolve, reject);
});
})).then(resolve, reject);
});
};
这样写似乎也是并行的?
const PromiseForEach = (objects,asyncDosometing) => {
let result = Promise.resolve();
objects.forEach((obj) => {
result = result.then(asyncDosometing(obj));
});
return result;
}
// 测试结果为
// 直接打印了“成功” data为undefined 之后 一次性打印出所有“number”
// 而不是 每隔2s打印一个number number都打印完后 打印成功 并且data应给是个number数组
const list = [];
for (let i = 0; i < 100; ++i) {
list.push(i);
}
PromiseForEach(list, (number) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(number);
return resolve(number);
}, 2000);
})
}).then((data) => {
console.log("成功");
console.log(data);
}).catch((err) => {
console.log("失败");
console.log(err)
});
两种写法貌似有有问题呢
到是用async/await实现了
虽然不知道对不对啊 但是实现了预期
const PromiseForEach = async(objects, asyncDosometing) => {
let result = [];
for (let obj in objects) {
try {
result.push(await asyncDosometing(obj));
} catch (err) {
return err;
}
}
return result;
};
请问用Promise实现这种逻辑的正确的写法是怎么样的?求解!谢谢!!!
第二种方式的正确的
http://runjs.cn/code/ilckwwjy
如果需要返回结果的话, 可以再加一层 Promise