How do I handle asynchronous callbacks in an if-else statement?

For a project, I need to change some values ​​in the file in five if-statements that are executed one after the other, and after all this is done, I need to save the file. One of the changes contains the function of asynchronous image saving. The problem I'm running into is that this function hasn't been completed by the time the program hits the file write. How do I handle callbacks in an if-statement? The save image function must be executed before the program proceeds to the 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 anyone give me a pointer on how to handle this? Thank you! Regards, Eva

+3


source to share


3 answers


You can use an async library, specifically its control flow series

. https://caolan.github.io/async/docs.html#series

You want to execute your if statements as tasks in an array (first argument). Make sure to call the callback when asynchronous actions are performed. The second argument is a callback that will be executed when all your tasks are done.



async.series([
    function(callback){
        if(criterium1) {
          //Alter file
          // make sure to call the callback
        } else {
          callback(null, null);
        }
    },
    function(callback){
        if(criterium2) {
          //Alter file
          // make sure to call the callback
          // looks like you can just pass callback into the saveImage function
        } else {
          callback(null, null);
        }
    }
], function () {
  fs.writeFile(opfFile, xml, function(error) {
    callback(null);
 });
});

      

+1


source


as Transcendence said, async is really good for this kind of streams.

I just wrote a simple async-if-else module because I had a similar problem in the stages of my chain.

async.waterfall([
   async.if(criterium1, fnCriterium1),
   async.if(criterium2, fnCriterium2),
   async.if(criterium3, fnCriterium3).else(fnCriteriumAlternative)
 ], handler);

      



Hope this helps you!

amuses

+4


source


Try to wrap all the functions inside a promise

0


source







All Articles