What is the difference between JavaScript promises and async await?

bozzmob picture bozzmob · Dec 21, 2015 · Viewed 40.7k times · Source

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.

Answer

Josh Beam picture Josh Beam · Dec 21, 2015

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