我正在尝试同时使用异步和请求模块,但我不明白回调是如何传递的。我的代码是
var fetch = function(file, cb) {
return request(file, cb);
};
async.map(['file1', 'file2', 'file3'], fetch, function(err, resp, body) {
// is this function passed as an argument to _fetch_
// or is it excecuted as a callback at the end of all the request?
// if so how do i pass a callback to the _fetch_ function
if(!err) console.log(body);
});
我正在尝试按顺序获取 3 个文件并连接结果。我的头脑陷入了我尝试过的回调和我能想到的不同组合中。 Google 帮不上什么忙。
最佳答案
Request 是异步函数,它不返回任何东西,当它的工作完成时,它会回调。来自 request examples ,你应该这样做:
var fetch = function(file,cb){
request.get(file, function(err,response,body){
if ( err){
cb(err);
} else {
cb(null, body); // First param indicates error, null=> no error
}
});
}
async.map(["file1", "file2", "file3"], fetch, function(err, results){
if ( err){
// either file1, file2 or file3 has raised an error, so you should not use results and handle the error
} else {
// results[0] -> "file1" body
// results[1] -> "file2" body
// results[2] -> "file3" body
}
});
关于node.js - 使用 nodejs 异步和请求模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11062995/