i need call callback inside recursive function when iterator bigger value or succesfully write requested image file, try , recieve error:
error: callback called.
here code:
async.each(products, function(product, callback) { var = 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) // 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 downloaded ' + localpath + fileextension); } }); }else { fetchimage(url, localpath, index + 1, iteration, fetchcallback); //try extension } } }); }
there @ least 1 problem in code :
if condition iteration > 2 || index === extensions.length true fetchcallback called 2 times async callback called 2 times.
i suggest change if (iteration > 2 || index === extensions.length) { fetchcallback(null)}; if (iteration > 2 || index === extensions.length) { return fetchcallback(null)};
Comments
Post a Comment