在异步循环中等待诺言

时间:2018-07-12 13:14:40

标签: javascript node.js loops promise

为什么此代码段无法按预期方式工作,因此在对象填充数据之前调用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);

2 个答案:

答案 0 :(得分:4)

外部.map()调用中的函数不会返回任何内容,因此Promise.all不会得到任何等待的保证。

解决方案是将内部map()包装在Promise.all(...)中并返回:

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

答案 1 :(得分:-1)

简单解决方案1:

enter image description here

enter image description here

解决方案2:

您也可以使用

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}
});
相关问题