mercredi 22 avril 2015

Javascript - if with asynchronous case

My question is a bit regards concept.

A lot of times there is this such situation:

if(something){
    someAsyncAction();
}else{
    someSyncAction();
}

// Continue with the rest of code..
var a = 5;

The problem with this such case is clear, i don't want the var a = 5 to be call unless someAsyncAction() or someSyncAction() will done, now, cause soAsyncAction() is asynchronous the only way (i can think of) to solve this situation is something like that:

var after = function(){
    // Continue with the rest of code..
    var a = 5;
}

if(something){
    someAsyncAction(after);
}else{
    someSyncAction();
    after ();
}

BUT, this code is ugly, hard to read and looks like anti-pattern and problematic.

I trying to think maybe i can find some solution for that with Promises (using Bluebird at the backend) but can't find something.

Is anyone faced this before and can help me figure it out?

Thanks!

Aucun commentaire:

Enregistrer un commentaire