javascript - 使用异步函数添加到数组

标签 javascript arrays node.js asynchronous promise

假设我有一个文件数组 file_urls,我想解析并将结果添加到结果数组中:

var requestImageSize = require('request-image-size');

function parse_file(file) {
    return new Promise(function(resolve, reject) {
        /*this is an asynchronous function from an external library,
         it returns attributes about the file such as its size and dimensions
        */
        requestImageSize(file).then(function(result) { 
            resolve(result);            
        }
        .catch(function(err) {
            reject(err);
        });   
    })
}
var results = [];
var promise;

//assume file_urls is already populated with strings of urls to files
file_urls.each(function(index, elem) {
    //if it's the last element then return the promise so we can return the final results at the end
    if (index == file_urls.length-1) {
        promise = parse_file(this);
    }
    //otherwise process the promise
    else {
        parse_file(this).then(function(result) {
            results.push(result);
        }
    }
});

//add the final element and return the final results
promise.then(function(result) { 
    results.push(result);
    return result;
});

由于 parse_file 返回一个 promise ,并且我正在迭代许多 promise ,因此如何确保结果数组具有正确的元素数量(以及可能的顺序)?

到目前为止,在我的项目中,它返回的元素数量不稳定,我应该采取什么不同的做法?

最佳答案

您要查找的惯用法是 Promise.all.map 组合:

Promise.all(file_urls.map(parse_file)).then(results => ...)

Promise.all 确保您以正确的顺序获得所有结果,但它不会强制执行任何特定的执行顺序。

关于javascript - 使用异步函数添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46333561/

相关文章:

arrays - 递归消除元胞数组中的数字

java - TDD 仅适用于模型或其他地方

ios - 对象数组与不同的数组

c - 在C中形成数组并打印列/行

node.js - 从 firebase 函数连接到 MongoDB Atlas

python服务器和node.js web客户端连接

javascript - 为什么打开页面后无法隐藏内容?

javascript - 使用 Select2 Ajax 填充选择选项

javascript - 可以生成 Firebase UID 的短链接吗?

javascript - 仅在执行某些事件后才打开链接中的 href