0

I use the following code

request(firstparams, function () {
    var secondparams = {
    // ******
    };

    request(secondparams, function () {
        for (i=0; i<3; i++) {
            var thirdparams = {
            // ******
            };

            request(thirdparams, function () {
                console.log('foo');
            });
        }
        console.log('bar');
    });
}); 

and want to get the result like:

foo
foo
foo
bar

but the result is:

bar
foo
foo
foo

Sorry for my poor English, if there is something ambiguity,I would try my best to explain. Thanks a lot ^ ^

viosey
  • 3
  • 1
  • 4
  • 1
    have a look at http://stackoverflow.com/questions/5010288/how-to-make-a-function-wait-until-a-callback-has-been-called-using-node-js – Derlin Feb 11 '17 at 13:22

1 Answers1

0

The easies way to do what you want would be to use 'async' module which is the classical module to handle async problems.

To run 3rd calls in parallel and log 'bar' after each of them is finished you would do something like this:

const async = require('async');

let asyncFunctions = [];
for (let i = 0; i < 3; i+= 1) {
 let thirdParams = {...};

 asyncFunctions.push(function (callback) {
  request(thirdparams, function (err, data) {
   console.log('foo');
   callback(err, data);
  });
 });
}

async.parallel(asyncFunctions, function (err, data) {
 console.log('bar');
});

You are using callbacks. But there are also other ways to handle asynchrony in node.js like: promises, generators and async/await functions from ES7.

I think that may be useful for you do check out some articles like this one.

Antonio Narkevich
  • 4,206
  • 18
  • 28