Wednesday, 24 May 2017

Node JS: chaining promises which are using promises

I need to chain promises which are using request promises, so it is kinda chaining nested promises.

Imagine the code:

const rp = require('request-promise');

function doStuff(){
  for ( let i = 0; i <= 10; i++ ){
    methodA();
  }
};

function methodA(){
  let options = {...};
  rp(options)
    .then(result => methodB(result))
    .catch(err => console.log(err));
};

function methodB(resultA){
  let options = {uri: resultA};
  rp(options)
    .then(result => methodC(resultA, result))
    .catch(err => console.log(err));
};

function methodC(resultA, resultB){
  //some calculations
};

In doStuff I need to wait for result of all ten executions of methodC and collect them into array. I have tried to chain it like that:

function doStuff(){
  for ( let i = 0; i <= 10; i++ ){
    let promiseA = new Promise((resolve, reject) => {
      resolve(methodA());
    });
    let promiseB = promiseA.then(result => methodB(result));
    let promiseC = promiseB.then(result => methodC(promiseA.result, result));
    Promise.all([promiseA, promiseB, promiseC]);
  }
};

But for sure it won't work, because in methodA and methodB we have HTTP requests which are asynchronous. Therefore, result in promiseB is undefined.

It means, the question is: how to chain promises, if they have nested promises? (and how to collect result in the end?)

Thanks!



via user1152126

No comments:

Post a Comment