假设我有一个文件数组 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/