Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 694
patz Avatar asked Feb 18 '26 20:02

patz


1 Answers

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.

like image 96
Kevin B Avatar answered Feb 20 '26 10:02

Kevin B



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!