Eva
Eva

Reputation: 323

How to handle asynchronous callbacks within an if - else statement?

For a project I need to alter some values in a file in five if-statements that are executed one after another, and after all those things are done, I need to save the file. One of the alteration contains an asynchronous save image function. The problem I'm having is that that function has not finished by the time the program gets to the file writing. How should I handle the callbacks within the if-statement? The save image function should 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 any pointer on how to handle this? Thanks! Kind regards, Eva

Upvotes: 3

Views: 7488

Answers (3)

Transcendence
Transcendence

Reputation: 2696

You can use the async library, specifically its series control flow. https://caolan.github.io/async/docs.html#series

You want to execute your if statements as tasks in the array (first argument). Make sure to call the callback when your asynchronous actions are done. The second argument is a callback that will execute 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);
 });
});

Upvotes: 1

CHAPa
CHAPa

Reputation: 677

as Transcendence said, async is really good for that kind of flow.

I just wrote a simple async-if-else module, because I had a similar problem on my chain steps.

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

I hope this could help you !

cheers

Upvotes: 4

Sathish
Sathish

Reputation: 2180

Try wrapping all functions inside a promise

Upvotes: 0

Related Questions