简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM