I found many similar questions but none with the same purpose (or maybe i just didnt understand? Can be that as well).
I've an array of elements, a function A that performs an async operation with an element and returns a promise, and the function B i'm working on which should call A for each array element, and return a promise once all the A calls have been completed. How can i do that? Relevant code:
var img = [];
img[0] = "http://www.something.com/picture0.jpg";
img[1] = "http://www.something.com/picture1.jpg";
img[2] = "http://www.something.com/picture2.jpg";
function ask(img)
{
return new Promise((resolve, reject) =>
{
if(something)
{resolve("test");}
else
{reject("test");}
}
}
function analyze_all(img)
{
for(var i in img)
{
ask(img[i])
.then((res) =>
{
???
})
.catch((err) =>
{
???
});
}
return ???
}
I thought about pushing all results to a list, like that:
function analyze_all(img)
{
var ret = [];
for(var i in img)
{
ask(img[i])
.then((res) =>
{
ret.push({image: img[i], data: res});
})
.catch((err) =>
{
ret.push({image: img[i], error: err});
});
}
return ???
}
But then how do i know when will all the async calls be completed? Please help!
Solved. As addition, if someone has similar needs and wants to have all the "return" values whether they're resolves or rejects, i suggest checking the following link: https://nmaggioni.xyz/2016/10/13/Avoiding-Promise-all-fail-fast-behavior/