3

如果我使用此代码:

async.eachLimit(body.photos.photo, 10, function(photo) {

         var flickr_getphoto_path = ".....";

         request.get({url: flickr_host_url + flickr_getphoto_path, json: true}, function(error, response, body) {
           if (!error && response.statusCode == 200) {

             console.log("SIZES LENGTH: " + body.sizes.size.length);
             var source_url = body.sizes.size[body.sizes.size.length - 1].source;
             request(source_url).pipe(fs.createWriteStream(path_for_downloads + path.basename(source_url)));
           }
         });

}

处理在 10 个请求后停止(即在第一个周期之后)。应该有10个周期。

有人知道为什么它不能正常工作吗?

4

1 回答 1

5

您错误地设置了异步功能。第三个参数(迭代器函数)有两个参数:被迭代的项目,以及一个告诉异步它已经完成的回调。你错过了(因此永远不会调用)回调,所以 async 不知道是时候做下一批了。

var async = require('async');

async.eachLimit(body.photos.photo, 10, cacheOnePhoto, function(err){
  if(err){
    console.log(err);
  } else {
    console.log('Processing complete');
  };
})

function cacheOnePhoto(photo, done){
  var flickr_getphoto_path = ".....";
  request.get({
    url: flickr_host_url + flickr_getphoto_path, 
    json: true
  }, function(error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log("SIZES LENGTH: " + body.sizes.size.length);
      var source_url = body.sizes.size[body.sizes.size.length - 1].source;
      request(source_url).pipe(
        fs.createWriteStream(path_for_downloads + path.basename(source_url))
      );
      done(null);
    } else {
      done('Request error for '+flickr_getphoto_path);
    }
  });
};
于 2013-06-21T13:54:16.020 回答