【问题标题】:Adding to an array with an asynchronous function使用异步函数添加到数组
【发布时间】:2018-03-02 04:39:29
【问题描述】:

假设我有一个文件数组,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使用它之前会导致兼容性问题。以及一般使用承诺。另一种选择是使用回调。如果回调已被调用 x 次(x 表示数组长度),则返回必要的值。

标签: javascript arrays node.js asynchronous promise


【解决方案1】:

您要查找的成语是Promise.all 结合.map

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-30
    • 2015-08-18
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多