TC39 (committee responsible for ECMAScript) conservatism in adding new semantics and syntax is pretty well known. ES5 came out in 2009 and the next large version called ECMAScript 2015 (formerly: ES6) was released in 2015. You could expect that after six years the changes in the language would be revolutionary. And in some sense they are, since JavaScript has never gone through so many changes. Yet in comparison to Python release cycle you could say those changes are cosmetic at best.

Solutions such as Promises or generators are good foundation for most applications. You can implement any control flow with them.

 

What generators actually are

Considering the theory of programming, generators are a particular case of coroutines. In theory a coroutine is a procedure (or function, or method) that retains its execution state between consecutive calls.

Consider the following code:

     function* ourGenerator(){
          for(var i = 0; i < 5; i++)
                yield i;
     }
     const gen = ourGenerator();
     gen.next(); // {done: false, value: 0}
     gen.next(); // {done: false, value: 1}
     …
     gen.next(); // {done: true}

As you can see, the next step could be executed at any time. Furthermore, the generators allow to send messages back to the code:

     function* ourGenerator(){
          for(var i = 0; i < 5; i++)
                i = yield i;
     }
     let gen = ourGenerator();
     gen.next(); // {done: 0, value: 0}
     gen.next(); // {done: false, value: undefined}
     gen.next(); // {done: true}
     gen = ourGenerator();
     gen.next();
     gen.next(3); // {done: false, value: 4}
     gen.next(3); // {done: false, value: 4}

The value of expression „yield…” is being replaced by the first argument of the following execution of the next() method. What would happen if Promise became the result of the expression? Can we use this functionality to write asynchronous code that looks synchronous?

My first thought is to yield Promise from the generator and send back the actual data. Something like this:

          const users = {get: email=>Promise.resolve({name: ‘Foo Bar’, email: email}));
     function getUser() {
          const user = wait for users.get(‘foo@bar.com’);
          console.log(user); // {name: ‘Foo Bar’, ‘email’: ‘foo@bar.com’}
     }

That functionality, but inspired by similar C# async-await syntax, is a proposition to ECMAScript 2017. It is now on development stage 3 of 5.

     async function getUser(){
          const user = await users.get(‘foo@bar.com’);
          console.log(user);
     }

Async-await is a breakthrough in the world of JavaScript. Promises freed us from nesting callbacks indefinitely (so called callback hell). Async-await goes one step further, because synchronous and asynchronous codes are basically indistinguishable.

async function throwCatch() {
     try {
          await Promise.reject(new TypeError(‘throwed’));
     } catch(e) {
          console.log(e); // TypeError: throwed
     }
}

Simplicity and clarity of this model is evident to any imperative language programmer. I will show you how to download files orderly using Fetch API:

     function fetchAll(urls=[]) {
          const ret = {};
          for(const url of urls) {
                          ret[url] = await fetch(url);
                   }
          return ret;
     }

It’s extremely easy to move from doing things orderly to concurrent downloads:

          for(const {url,promise} of urls.map(url=>({url, promise: fetch(url)})) {
                          ret[url] = await promise;
                   }

 

Async-await lets you avoid using antipatterns

It is a truth universally acknowledged, that every developer sometimes makes mistakes. From simple errors such as typos, up to using antipatterns. One of the most popular antipatterns is using new Promise. All too often we see code looking like this:

     return new Promise((resolve, reject) => {
          $http.get(‘url’)
               .then(data=>resolve(data))
               .catch(err=>reject(err));
     });

Nesting long closures into asynchronous function stands out a lot. You can clearly see that something is terribly wrong here:

async function fooBar() {
     new Promise((resolve, reject) => {
               $http.get(‘url’)
                    .then(data=>resolve(data))
                    .catch(err=>reject(err));
          });
}

What the programmer needs is this:

Promise.resolve($http.get(‘url’)); //

 


Async-await solves different problems than Promises do

Promises are, in principle, monad-like. They wrap the value that will be available in the future and enable using it the moment it becomes accesible. Conceptually speaking, they are based on and limited to value passing. Using Promises to execute asynchronous code is, in fact, abusing them.

 

Async-await is too much of a bleeding edge for my company/my boss

You poor thing ;_; We have no such restrictions in our company. In this case though, I would recommend using the fantastic Bluebird library and the function Promise.coroutine.