为什么此代码片段无法按预期工作,导致在对象填充数据之前调用 console.debug(images)
?我希望两个循环并行运行,但是 await Promise.all
应该等待循环完成。第一个循环和第二个循环应该同时运行。
const images = {
taskImages: [],
solutionImages: []
};
await Promise.all(Object.keys(files).map((key) => {
files[key].map(async (file) => {
const fileId = getFileId(file.path);
const result = await storeImage(fileId, file.path);
if (result) {
images[key].push(fileId);
console.debug("Pushed " + key);
}
});
}));
console.debug(images);
最佳答案
外部 .map()
调用中的函数不会返回任何内容,因此 Promise.all
不会等待任何 Promise。
解决方案只是将内部 map()
包装在 Promise.all(...)
中并返回:
await Promise.all(Object.keys(files).map((key) => {
return Promise.all(files[key].map(async (file) => {...}));
}));
关于javascript - 在异步循环中等待 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51306689/