samedi 25 avril 2015

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

Aucun commentaire:

Enregistrer un commentaire