内容简介:翻译自:https://stackoverflow.com/questions/11062995/using-nodejs-async-and-request-module
我正在尝试一起使用异步和请求模块,但我不明白回调是如何传递的.我的代码是
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个文件并连接结果.我的头脑陷入了我试过的回调和我能想到的不同组合.谷歌帮助不大.
请求是异步函数,它不会返回一些东西,当它的工作完成时,它会回调.从 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
}
});
翻译自:https://stackoverflow.com/questions/11062995/using-nodejs-async-and-request-module
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Spring框架高级编程
约翰逊 / 蒋培 / 机械工业出版社 / 2006-4 / 59.00元
Spring框架是主要的开源应用程序开发框架,它使得Java/J2EE开发更容易、效率更高。本书不仅向读者展示了Spring能做什么?而且揭示了Spring完成这些功能的原理,解释其功能和动机,以帮助读者使用该框架的所有部分来开发成功的应用程序。本书涵盖Spring的所有特性,并且演示了如何将其构成一个连贯的整体,帮助读者理解Spring方法的基本原理、何时使用Sping以及如何效仿最佳实践。所有......一起来看看 《Spring框架高级编程》 这本书的介绍吧!