Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining promise results in Javascript

I have two functions which return a Promise. The first one returns a list of values that I want to iterate through and make a second call on each, accumulating to the result to send back.

function firstCall() {
 return new Promise(returns list of items);
}

function secondCall(someVal) {
  return new Promise(return single value);
}

function doSomething() {
  firstCall().then((response1) => {
    response1.someResult.map((item) => {
      secondCall(item).then((response2) => {
        //how to collect all?
      });
   });
  });
}

Any suggestion on how I can chain these Promise returning call and returning list of final result?

like image 930
αƞjiβ Avatar asked May 24 '26 15:05

αƞjiβ


1 Answers

I'm presuming that you are using ES6 or some polyfill (Bluebird, etc.) If that isn't the case, please update your question. If so, you can send an array of Promises to Promise.all() and get an array of answers back.

function firstCall() {
  return new Promise((resolve, reject) => {
    resolve([1, 2, 3, 4, 5, 6]);
  })
}

function secondCall(n) {
  return new Promise((resolve, reject) => {
    resolve(n * n);
  })
}

function doSomething() {
  firstCall()
    .then(response1 => {
      console.log(response1);
      let promises = response1.map(r => secondCall(r));

      Promise.all(promises)
        .then(response2 => {
          console.log(response2);
        })
    })
}

doSomething();
like image 94
mherzig Avatar answered May 27 '26 03:05

mherzig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!