本文介绍了为什么Node.js的异步模块使用async.eachLimit第一步(数组,极限,函数,回调)后停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我用这个code:
If I use this code:
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个周期。
The processing stops after 10 requests (i.e. after the first cycle).There should be 10 cycles.
是否有人知道为什么它不能正常工作?
Does somebody know why it doesn't work properly?
推荐答案
您设置了异步功能失常。第三个参数(迭代器功能)有两个参数:项目在被迭代,并且回调来告诉异步,它的完成。你错过了(因此永远不会调用)回调,因此异步不知道它的时间做下一批次。
You set up the async function wrong. The third argument (the iterator function) takes two parameters: the item being iterated upon, and a callback to tell async that it's done. You're missing (and thus never calling) the callback, so async doesn't know that it's time to do the next batch.
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);
}
});
};
这篇关于为什么Node.js的异步模块使用async.eachLimit第一步(数组,极限,函数,回调)后停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!