node.js - How to handle asynchronous callbacks within an if - else statement? -
for project need alter values in file in 5 if-statements executed 1 after another, , after things done, need save file. 1 of alteration contains asynchronous save image function. problem i'm having that function has not finished time program gets file writing. how should handle callbacks within if-statement? save image function should executed before program proceeds next if statement.
if(criterium1){... //alter file} if(criterium2){ saveimage(searchvalue, folder,callback(error)){ ... //alter file } if(criterium3){... //alter file} fs.writefile(opffile, xml, function(error) { callback(null); }); var saveimage = function(searchvalue, folder, callback){ var images = require ('google-images2'); images.search(searchvalue, function(error, image){ callback(null); }); };
can give me pointer on how handle this? thanks! kind regards, eva
you can use async library, series
control flow. https://caolan.github.io/async/docs.html#series
you want execute if statements tasks in array (first argument). make sure call callback when asynchronous actions done. second argument callback execute when tasks done.
async.series([ function(callback){ if(criterium1) { //alter file // make sure call callback } else { callback(null, null); } }, function(callback){ if(criterium2) { //alter file // make sure call callback // looks can pass callback saveimage function } else { callback(null, null); } } ], function () { fs.writefile(opffile, xml, function(error) { callback(null); }); });
Comments
Post a Comment