What is the difference between JavaScript promises and async await?


I have been using ECMAScript 6 and ECMAScript 7 features already (thanks to Babel) in my applications - both mobile and web.

The first step obviously was to ECMAScript 6 levels. I learnt many async patterns, the promises (which are really promising), generators (not sure why the * symbol), etc. Out of these, promises suited my purpose pretty well. And I have been using them in my applications quite a lot.

Here is an example/pseudocode of how I have implemented a basic promise-

var myPromise = new Promise(
    function (resolve,reject) {
      var x = MyDataStore(myObj);
      resolve(x);
    });

myPromise.then(
  function (x) {
    init(x);
});

As time passed, I came across ECMAScript 7 features, and one of them being ASYNC and AWAIT keywords/functions. These in conjunction do great wonders. I have started to replace some of my promises with async & await. They seem to add great value to programming style.

Again, here is a pseudocode of how my async, await function looks like-

async function myAsyncFunction (myObj) {
    var x = new MyDataStore(myObj);
    return await x.init();
}
var returnVal = await myAsyncFunction(obj);

Keeping the syntax errors (if any) aside, both of them do the exact same thing is what I feel. I have almost been able to replace most of my promises with async,awaits.

Why is async,await needed when promises do a similar job?

Does async,await solve a bigger problem? Or was it just a different solution to callback hell?

As I said earlier, I am able to use promises and async,await to solve the same problem. Is there anything specific that async await solved?

Additional notes:

I have been using async,awaits and promises in my React projects and Node.js modules extensively. React especially have been an early bird and adopted a lot of ECMAScript 6 and ECMAScript 7 features.

Async/Await provide a much nicer syntax in more complex scenarios. In particular, anything dealing with loops or certain other constructs like try/catch.

For example:

while (!value) {
  const intermediate = await operation1();
  value = await operation2(intermediate);
}

This example would be considerably more convoluted just using Promises.


Full comparison with pros and cons.

Plain JavaScript

  • Pros
  • Does not require any additional libraries or technology
  • O?ers the best performance
  • Provides the best level of compatibility with third-party libraries
  • Allows the creation of ad hoc and more advanced algorithms
  • Cons
  • Might require extra code and relatively complex algorithms

Async (library)

  • Pros
  • Simpli?es the most common control ?ow patterns
  • Is still a callback-based solution
  • Good performance
  • Cons
  • Introduces an external dependency
  • Might still not be enough for advanced ?ows

Promises

  • Pros
  • Greatly simpli?es the most common control ?ow patterns
  • Robust error handling
  • Part of the ES2015 speci?cation
  • Guarantees deferred invocation of onFulfilled and onRejected
  • Cons
  • Requires promisify callback-based APIs
  • Introduces a small performance hit

Generators

  • Pros
  • Makes non-blocking API look like a blocking one
  • Simpli?es error handling
  • Part of ES2015 speci?cation
  • Cons
  • Requires a complementary control ?ow library
  • Still requires callbacks or promises to implement non-sequential ?ows
  • Requires thunkify or promisify nongenerator-based APIs

Async await

  • Pros
  • Makes non-blocking API look like blocking
  • Clean and intuitive syntax
  • Cons
  • Requires Babel or other transpilers and some con?guration to be used today

Async/await can help make your code cleaner and more readable in cases where you need complicated control flow. It also produces more debug-friendly code. And makes it possible to handle both synchronous and asynchronous errors with just try/catch.

I recently wrote this post showing the advantages of async/await over promises in some common use cases with code examples: 6 Reasons Why JavaScript Async/Await Blows Promises Away (Tutorial)


Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem?

async/await simply gives you a synchronous feel to asynchronous code. It's a very elegant form of syntactical sugar.

For simple queries and data manipulation, Promises can be simple, but if you run into scenarios where there's complex data manipulation and whatnot involved, it's easier to understand what's going on if the code simply looks as though it's synchronous (to put it another way, syntax in and of itself is a form of "incidental complexity" that async/await can get around).

If you're interested to know, you can use a library like co (alongside generators) to give the same sort of feel. Things like this have been developed to solve the problem that async/await ultimately solves (natively).


Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem? or was it just a different solution to callback hell? As I said earlier, I am able to use Promises and Async,Await to solve the same problem. Is there anything specific that Async Await solved?

The first things you have to understand that async/await syntax is just syntactic sugar which is meant to augment promises. In fact the return value of an async function is a promise. async/await syntax gives us the possibility of writing asynchronous in a synchronous manner. Here is an example:

Promise chaining:

function logFetch(url) {
  return fetch(url)
    .then(response => response.text())
    .then(text => {
      console.log(text);
    }).catch(err => {
      console.error('fetch failed', err);
    });
}

Async function:

async function logFetch(url) {
  try {
    const response = await fetch(url);
    console.log(await response.text());
  }
  catch (err) {
    console.log('fetch failed', err);
  }
}

In the above example the await waits for the promise (fetch(url)) to be either resolved or rejected. If the promise is resolved the value is stored in the response variable, and if the promise is rejected it would throw an error and thus enter the catch block.

We can already see that using async/await might be more readable than promise chaining. This is especially true when the amount of promises which we are using increases. Both Promise chaining and async/await solve the problem of callback hell and which method you choose is matter of personal preference.