This blogpost explains how some nifty features in ES7 will make it easier to write asynchronous code, and how ES6 generators will pave the way for this.
This was slightly improved and simplified with ES6 promises, however, as we can see in the following code, we are still stuck with nested .then-calls:
The await keyword can either take a promise or an async function, and pauses until the promise resolves, or the async function returns. If the promise rejects or the async function throws an error, the error can be caught with a normal catch-statement. This provides a significant improvement in readability, which likely leads to less bugs and a pleasure to write.
Along with promises, ES6 brought generators, which allows a function to pause at a certain point (yield) and continue when requested with .next(), as illustrated in the following code:
Generators are not very useful for normal application logic, but they provide the buildings blocks for some nifty features.
However, because Safari and Internet Explorer don’t support generators yet, it is to early to start using generators on the front-end, however, on the backend with Node, it can be safely used, because async/await keywords are transpiled to generators.
A web framework in Node that is based around generators, and uses it for all it is worth, is Koa. They utilize generators to make the code behave similar to async/await:
The yield keyword behaves as await, and generator function* behaves as async functions. The main motivation for this is to simplify writing middlewares, and avoid the mentioned callback hell. In the next version of Koa, the yield keyword and generator functions will be replaced with await and async.
So, ES7 provides a fantastic improvement in simplifying asynchronous code that makes code easier to read and write. These features can already be used on the backend with Node and web frameworks like Koa.
Thanks to Sveinung Røsaker for improving the callback example.Tags: es6 es7