2015-10-17 135 views
0

從下面的代碼我沒有得到result1數據。它沒有定義。有人能幫助我嗎?回調未定義在async.waterfall方法

async.waterfall([ 
    function(callback) { 
     request({ 
      method: 'GET', 
      headers: { 
       'Content-Type': 'application/json' 
      }, 
      url: url 
     }, function(error, response, body) { 
      if (error) { 
       callback(error); 
      } else { 
       var result = JSON.parse(body); 
       callback(null, result); //sending to next function 
      } 
     }); 
    }, 
    function(result, callback) { 

     async.eachSeries(result, function(item, callback) { 
      request({ 
       method: 'GET', 
       headers: { 
        'Content-Type': 'application/json' 
       }, 
       url: url+item.id 
      }, function(error, response, body) { 
       if (error) { 
        callback(error); 
       } else { 
        var result1 = JSON.parse(body); 
        callback(null, result1); 
       } 
      }); 
     }, function(err, result1) { 
      if (!err) { 
       callback(null, result1); 
      } else { 
       callback(err); 
      } 
     }); 
    }, 
    function(result1, callback) { 
     console.log(result1); // getting undefined 
     request({ 
      method: 'GET', 
      headers: { 
       'Content-Type': 'application/json' 
      }, 
      url: url 
     }, function(error, response, body) { 
      if (error) { 
       callback(error); 
      } else { 
       var result2 = JSON.parse(body); 
       callback(null, result2); 
      } 
     }); 
    } 
], function(error, res) { 
    console.log(res); // process final result 
}); 

回答

2

對於eachSeries簽名看起來是這樣的 - 回調(ERR),沒有第二個參數,這就是爲什麼result1undefined

如果您需要的時候循環已經完成,你需要使用.mapSeries,像這樣得到的結果

async.mapSeries(result, function(item, callback) { 
    request({ 
    method: 'GET', 
    headers: { 
     'Content-Type': 'application/json' 
    }, 
    url: url + item.id 
    }, function(error, response, body) { 
    if (error) { 
     callback(error); 
    } else { 
     var result1 = JSON.parse(body); 
     callback(null, result1); 
    } 
    }); 
}, function(err, result1) { 
    if (!err) { 
    callback(null, result1); 
    } else { 
    callback(err); 
    } 
}); 
+0

'mapSeries'做了魔法。非常感謝。 –

相關問題