assume I have an array of files, file_urls, I want to parse through and add the results to a result array:
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;
});
Since parse_file returns a promise and I'm iterating through many promises, how do I ensure that the results array has the correct number (and possibly order) of elements?
so far in my project it is returning an erratic number of elements, what should I do differently?
Promise.AllUsing this has causes me compatibility issues before. As well as using promises in general. Another option would be to use callbacks. If the callback has been called x number of times (x representing the array length), then return the necessary values.