design patterns - Javascript - if with asynchronous case -
my question bit regards concept.
a lot of times there such situation:
if(something){ someasyncaction(); }else{ somesyncaction(); } // continue rest of code.. var = 5;
the problem such case clear, don't want var = 5
call unless someasyncaction()
or somesyncaction()
done, now, cause soasyncaction()
asynchronous way (i can think of) solve situation that:
var after = function(){ // continue rest of code.. var = 5; } if(something){ someasyncaction(after); }else{ somesyncaction(); after (); }
but, code ugly, hard read , looks anti-pattern , problematic.
i trying think maybe can find solution promises (using bluebird @ backend) can't find something.
is faced before , can me figure out?
thanks!
with promises, have similar pattern callback, store result first , not have call/pass callback twice:
function after(result) { // continue rest of code.. var = 5; } var promise; if (something){ promise = someasyncaction(); } else { promise = promise.resolve(somesyncaction()); } promise.then(after);
or in short, you'd use conditional operator , structure more straightforward:
(something ? someasyncaction() : promise.resolve(somesyncaction()) ).then(function(result) { // continue rest of code.. var = 5; });
Comments
Post a Comment