2015-10-17 36 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'做了魔法。非常感谢。 –