具有相同callback函数的多个请求asynchronous

var parsedUrl = req.body.parsedUrl; console.log(parsedUrl); var options = { url: 'https://api.github.com/repos/' + parsedUrl, headers: { 'User-Agent': 'request' } }; var options2 = { url: 'https://api.github.com/repos/' + parsedUrl + '/readme', headers: { 'User-Agent': 'request' } }; function callback(error, response, body) { if (!error && response.statusCode == 200) { var info = JSON.parse(body); Thing.create(info, function(err, thing) { //console.log(info); if(err) { return handleError(res, err); } return res.json(201, thing); }); } else { console.log('github request error'); } } request(options, callback); request(options2, callback); 

基本上,我需要做两个请求,所以我的问题如下:1.如何使用asynchronous模块asynchronous地使这两个请求。 我尝试过使用async.parallel,但是由于async.parallel需要callback,所以语法在请求语法上不能很好地发挥作用。

2.如何合并结果? 我需要将它们同时保存到Mongo中同一个对象的数据库中。

我希望这是有道理的。 谢谢,

您可以使用async库:

 npm install async --save 

使用optionsoptions2创build一个数组,并在数组中的每个项目上调用request

 async.map([options, options2], request, function(err, results) { // results[0] is the response for options // results[1] is the response for options2 // you can merge them here and insert into mongodb as one document });