node.js – 使用nodejs async和请求模块

综合技术 2019-01-12 阅读原文


var fetch = function(file, cb) {
    return request(file, cb);
};['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);


请求是异步函数,它不会返回一些东西,当它的工作完成时,它会回调.从 request examples

var fetch = function(file,cb){
     request.get(file, function(err,response,body){
           if ( err){
           } else {
                 cb(null, body); // First param indicates error, null=> no error
}["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


责编内容by:代码日志 【阅读原文】。感谢您的支持!