0

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?

Zach Smith
  • 8,458
  • 13
  • 59
  • 133
  • 2
    promises, callbacks and `async`/`await` are just all different ways to do the same thing. No one is (functionally) "better " than the other. It's just a way to write cleaner more readable code, i.e. a massive nested chain of callbacks is worse than a promise chain and the promise chain can be made simpler using `async`s. Nothing is fundamentally changed, they essentially do the same thing in (mostly) the same way. – Liam Mar 05 '18 at 11:08
  • Uh, your examples are not equivalent. The `return x` needs to go *inside* the (promise) callback if `x` is the asynchronous result. And without promises, a `return` in an asynchronous callback does simply not work. – Bergi Mar 05 '18 at 11:10
  • ah yes. the `x` in the async/await example is now `y` – Zach Smith Mar 05 '18 at 11:11
  • `that isn't immediately obvious?` `error handling`, `shorter stack`, `required for async / await`, and most importantly easier to understand code. – Keith Mar 05 '18 at 11:18

0 Answers0