簡體   English   中英

使用Node.js異步和請求模塊

[英]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個文件並連接結果。 我的頭陷入了我嘗試過的回調以及可以想到的各種組合中。 Google並沒有太大幫助。

請求是異步函數,它不返回任何內容,當其工作完成時,它會回調。 請求示例中 ,您應該執行以下操作:

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
    }
});

在您的示例中, fetch函數將被調用三次,對於作為第一個參數傳遞給async.map的數組中的每個文件名,將調用一次。 第二個回調參數也將傳遞給fetch ,但該回調由async框架提供,您必須在fetch函數完成其工作時調用它,並將其結果作為第二個參數提供給該回調。 您提供的第三個參數回調async.map當所有三個將被稱為fetch來電呼吁向他們提供的回調。

參見https://github.com/caolan/async#map

因此,要在代碼中回答您的特定問題,您提供的回調函數將在所有請求結束時作為回調執行。 如果您需要傳遞回調以進行fetch可以執行以下操作:

async.map([['file1', 'file2', 'file3'], function(value, callback) {
    fetch(value, <your result processing callback goes here>);
}, ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM