简体   繁体   中英

node.js - nesting request, wait until request function is done

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 ^ ^

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 .

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