patz
patz

Reputation: 1316

for loop in nodejs using q library

The following are the functions I have

function start(){
 var deferred = Q.defer();
  for(var i=0; i < 3; i++){
    second()
      .then(third)
      .then(fourth)
      .catch(function(error){
        console.log(error);
      });
  }
  return deferred.promise;
}

function second(){
//does an http request
// returns promise
}

function third(){
//does an http request
// returns promise
}

function fourth(){
//takes the response of second and third function
//and compares the response
//returns promise
}

Here is the sequence of operations when the file is run:

second function
second function
third function
third function 
fourth function
fourth function

(I know why this is happening, its due to the I/O request in second and third function)

The sequence of operations I want

second function
third function
fourth function
second function
third function
fourth function

How do I accomplish this in nodejs?

Here is a follow up to the above question: how to pass values to the functions in the .then(funcCall(value)) so that when the function is actually called it also get a value which it can work on.

Upvotes: 3

Views: 171

Answers (1)

Kevin B
Kevin B

Reputation: 95057

You're halfway there, you just need to chain properly:

function start() {
  var deferred = Promise.resolve();
  for (var i = 0; i < 3; i++) {
    deferred = deferred.then(second)
      .then(third)
      .then(fourth)
      .catch(function(error) {
        console.log(error);
      });
  }
  return deferred.promise;
}

function second() {
  return new Promise(function(r) {
    console.log('second');
    setTimeout(r, 100);
  });
}

function third() {
  return new Promise(function(r) {
    console.log('third');
    setTimeout(r, 100);
  });
}

function fourth() {
  return new Promise(function(r) {
    console.log('fourth')
    setTimeout(r, 100);
  });
}
start();

Replace Promise with Q.

Upvotes: 3

Related Questions