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.我如何使用 async 模块异步发出这两个请求。我尝试使用 async.parallel 但该语法与请求的语法不能很好地配合,因为 async.parallel 需要回调。
2.如何合并结果?我需要将它们同时保存到数据库中的Mongo中的同一个对象中。
我希望这是有道理的。 谢谢,
最佳答案
您可以使用async
库:
npm install async --save
使用 options
和 options2
创建一个数组,并对数组中的每个项目调用 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
});
关于node.js - 使用相同的回调函数异步多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26602159/