What is the difference between JavaScript promises and async await?

JavascriptAsynchronousPromiseAsync Await

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

> 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 https://github.com/tj/co">`co`</a> (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).

Solution 2 - Javascript

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.

Solution 3 - Javascript

> 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.

Solution 4 - Javascript

Full comparison with pros and cons.

Plain JavaScript

  • Pros

> - Does not require any additional libraries or technology > - Offers 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

>

  • Simplifies the most common control flow patterns

  • Is still a callback-based solution

  • Good performance

  • Cons

>

  • Introduces an external dependency
  • Might still not be enough for advanced flows

Promises

  • Pros

>

  • Greatly simplifies the most common control flow patterns

  • Robust error handling

  • Part of the ES2015 specification

  • 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

  • Simplifies error handling

  • Part of ES2015 specification

  • Cons

>

  • Requires a complementary control flow library
  • Still requires callbacks or promises to implement non-sequential flows
  • 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 configuration to be used today

Solution 5 - Javascript

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)

Solution 6 - Javascript

await/async are often referred to as syntactic sugar to promises and let us wait for something (e.g. an API call), giving us the illusion that it is synchronous in an actual asynchronous code, which is a great benefit.

The things you want to achieve with async/await is possible with promises (but without the advantages of async/await). Lets take an example with this code:

const makeRequest = () => //promise way
  getJSON()
    .then(data => {
      return data
    })

makeRequest();

const makeRequest = async () => { //async await way
  const data = await getJSON();
  return data;
 }

makeRequest()

Why is async/await prefered over promises?

  1. Concise and clean - We don’t have to write .then and create an anonymous function to handle the response, or give a name data to a variable that we don’t need to use. We also avoided nesting our code. async/await is a lot cleaner.

  2. Error handling - Async/await makes it finally possible to handle both synchronous and asynchronous errors with the same try/catch format.

  3. Debugging - A really good advantage when using async/await is that it’s much easier to debug than promises for 2 reasons: 1) you can’t set breakpoints in arrow functions that return expressions (no body). 2) if you set a breakpoint inside a .then block and use debug shortcuts like step-over, the debugger will not move to the following .then because it only “steps” through synchronous code.

  4. Error stacks - The error stack returned from the promises chain gives us no idea of where the error occurred and can be misleading. async/await gives us the error stack from async/await points to the function that contains the error which is a really big advantage.

Solution 7 - Javascript

Await syntax is simply synchronous code because you have to wait until the promise is fulfilled or rejected. Actually code execution after await keyword will be suspended until the promise resolve or reject.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbozzmobView Question on Stackoverflow
Solution 1 - JavascriptJosh BeamView Answer on Stackoverflow
Solution 2 - JavascriptStephen ClearyView Answer on Stackoverflow
Solution 3 - JavascriptWillem van der VeenView Answer on Stackoverflow
Solution 4 - JavascriptBozhinovskiView Answer on Stackoverflow
Solution 5 - JavascriptgafiView Answer on Stackoverflow
Solution 6 - JavascriptRan TurnerView Answer on Stackoverflow
Solution 7 - Javascriptmahdi salmanizadeganView Answer on Stackoverflow