如果我使用此代码:
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个周期。
有人知道它为什么不能正常工作吗?
答案 0 :(得分: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);
}
});
};