I'm very familiar with using callbacks in JavaScript to serialize logic in an asynchronous environment. Compared to using async/await
in C# (and I believe this is coming to JavaScript), where you can do something like:
var y = await doAsynchronousNetWorkRequest();
return y;
I have found that promises offer very little improvement over handling asynchronous code vs callbacks.
With callback-based code, any logic that occurs after an asynchronous event gets placed in a callback:
(function() {
var x = 5;
makeAsyncRequest(function() {
// then do something
});
return x;
})();
x
will be returned before the then do something
component executes. Likewise with promises:
(function() {
var x = 5;
makeAsyncRequest()
.then(function() {
// then do something
})
return x;
})();
x
will STILL be returned before the then do something
component executes. And with respect to authoring your own library, aside from not having to include a callback parameter that is then executed at some point (i.e. it's ... slightly ... cleaner to just return a promise), as far as I can tell there is no functional difference between callback-based vs promise-based async code in the way that async/await
does actually make a difference. (And the 'flying v' doesn't appear in code bases, but that doesn't matter).
Is there any benefit to using promises vs callback based asynchronous code that isn't immediately obvious?