How to run multiple async functions then execute callback

后端 未结 3 803
甜味超标
甜味超标 2020-12-05 10:16

In my NodeJS code I need to make 2 or 3 API calls, and each will return some data. After all API calls are complete I want to collect all the data into a single JSON object

3条回答
  •  情深已故
    2020-12-05 10:40

    Sounds like async.parallel() would also do the job if you'd like to use async:

    var async = require('async');
    
    async.parallel({
        one: function(parallelCb) {
            request('http://www.example1.com', function (err, res, body) {
                parallelCb(null, {err: err, res: res, body: body});
            });
        },
        two: function(parallelCb) {
            request('http://www.example2.com', function (err, res, body) {
                parallelCb(null, {err: err, res: res, body: body});
            });
        },
        three: function(parallelCb) {
            request('http://www.example3.com', function (err, res, body) {
                parallelCb(null, {err: err, res: res, body: body});
            });
        }
    }, function(err, results) {
        // results will have the results of all 3
        console.log(results.one);
        console.log(results.two);
        console.log(results.three);
    });
    

提交回复
热议问题