简体   繁体   English

在异步循环中等待诺言

[英]Await promises in async loop

Why does this code snippet doesn't work as expected, so that console.debug(images) is called before the object is filled with data? 为什么此代码段不能按预期方式工作,所以在对象填充数据之前调用console.debug(images) I want the two loops to run parallel, but await Promise.all should wait for the loops to finish. 我希望两个循环并行运行,但是要await Promise.all应该等待循环结束。 Both the first loop and the second loop should run simultaneously. 第一个循环和第二个循环应同时运行。

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);

The function in the outer .map() call doesn't return anything, so Promise.all doesn't get any promises to wait for. 外部.map()调用中的函数不返回任何内容,因此Promise.all没有任何等待的承诺。

The solution is just to wrap the inner map() in Promise.all(...) and return that: 解决方案是将内部map()包装在Promise.all(...)并返回:

await Promise.all(Object.keys(files).map((key) => {
    return Promise.all(files[key].map(async (file) => {...}));
}));

Simple solution 1: 简单的解决方案1:

在此处输入图片说明

在此处输入图片说明

Solution 2: 解决方案2:

you also can use 你也可以使用

npm async library npm异步库

Link 链接

async.parallel({
    one: function(callback) {
        setTimeout(function() {
            callback(null, 1);
        }, 200);
    },
    two: function(callback) {
        setTimeout(function() {
            callback(null, 2);
        }, 100);
    }
}, function(err, results) {
    // results is now equals to: {one: 1, two: 2}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM