Reputation: 81
I am writing a script in node.js where I have method with a single parameter - id.
funcToCall(id)
{
// some code ...
returns a promise
}
var ids = [ list of ids] // input occurs dynamically
I will get a list of id's as input and I need to call the method with each input id in an asynchronous way. I have found a way to handle Promise.all() for the static/fixed number of method calls
const reflect = p => p.then(v => ({v, status: "fulfilled" }),
e => ({e, status: "rejected" }));
var arr = [ fun(id1), fun(id2), fun(id3) ]; // how to make this dynamically ?
Promise.all(arr.map(reflect)).then(function(results) {
var success = results.filter(x => x.status === "fulfilled");
});
Is there any possible way to dynamically call the method multiples times and in an asynchronous way?
Thanks in advance!!
Upvotes: 0
Views: 68
Reputation: 7770
You could use .map
on arrays and use Promise.all
like this
function funcToCall(id) {
return Promise.resolve(id); // this could be your promise.
}
const ids = [1, 2, 3, 4];
Promise.all(ids.map(id => funcToCall(id))).then((res = console.log(res)));
Upvotes: 1