假设我有一个文件数组,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,我如何确保结果数组具有正确的数字(可能是顺序)元素?
到目前为止,在我的项目中它返回了一些不稳定的元素,我应该做些什么呢?
答案 0 :(得分:2)
您正在寻找的成语Promise.all
与.map
相结合:
Promise.all(file_urls.map(parse_file)).then(results => ...)
Promise.all
确保您以正确的顺序获得所有结果,但它不会强制执行任何特定的执行顺序。