当迭代器大于某个值或者我成功地将请求的图像写入文件时,我需要在递归函数内调用回调,我尝试这样做,但我收到错误:
错误:已经调用了回调。
这是我的代码:
async.each(products, function(product, callback) {
var i = products.indexOf(product);
var pathNames = pathNormalizer(product.sku + "");
setTimeout(
function () {
fetchImage(pathNames[0],pathNames[1], 0, 0, function(err){
console.log("CALLBACK"); callback()
});
}, 150 * (i + 1) // where they will each progressively wait 150 msec more each
);
}, function(err) {
console.log("ASYNC EACH FINISH");
}
);
function fetchImage(url, localPath, index, iteration, fetchCallback) {
var extensions = ['jpg', 'png', 'jpeg', 'bmp' , ''];
var fileExtension;
if(extensions[index] === '' ) {
fileExtension = extensions[0];
}else{
fileExtension = extensions[index];
}
if (iteration > 2 || index === extensions.length) { fetchCallback(null)};
request.get(url + extensions[index], { encoding: null }, function(err,response,body) {
if(err || undefined === response){
setTimeout(function(){
console.log('Error URL : ' + url + extensions[index] + ' ' + err);
fetchImage(url, localPath, index, iteration,fetchCallback);
}, 200);
}else{
if(response.statusCode === 200) {
fs.writeFile('s' + localPath + fileExtension, body, 'binary', function(err){ //INTENTIONAL ERROR HERE (invalid path)
if (err){
setTimeout(function(){
console.log('Image saving error : ' + err + url + extensions[index]);
fetchImage(url, localPath, index, iteration +1, fetchCallback);
}, 500);
}else {
console.log('Image was successfully downloaded ' + localPath + fileExtension);
}
});
}else {
fetchImage(url, localPath, index + 1, iteration, fetchCallback); //try another extension
}
}
});
}