0

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!!

1
  • What does "dynamically call the method multiples times and in an asynchronous way" mean? I don't understand what problem you need to solve with your existing code based on Promise.all(). Commented Mar 21, 2020 at 19:48

1 Answer 1

1

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)));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.