Async/await is a new (and probably nicer) way to handle the asynchronous nature of JS. It’s currently (Aug 2016) in the stage 3 of ECMA spec, which means the spec is complete and the feature can become a candidate for next browser implementations.
I’ve recently tried to write an article to cover this new shiny syntax, but no good. The syntax is quite simple, but the basic knowledge to completely understand its background and behaviour is not so easy. I've failed in coming up with a neat structure for a post to make readers feel easy with it, at least til today. So, I’d once like to sum up my thoughts regarding async/await here. If I can be brave and feel ready enough, I may write a full-stretched guide later.
Many people may already know that Promise is a type of monad, specifically a Future monad. But to be honest, it is not 100% true. Promise is not just a Future monad, but a monad transformer of both Future and Either. Async/await just works the same as
donotation in Haskell works for
ErrorT Error Future. FYI,
ErrorTis a monad transformer for Either.
In Haskell, we can one-to-one replace
>>chaining. Now we can easily guess that we can also replace Promise with
thenchaining. However, transpilers like Babel doesn’t compile async/await into Promise, but into generator. One of the reasons may be synchronous try/catch statement. It is somewhat difficult to match try/catch with plain
thenchaining(surely it’s still possible though), when it's used with
async. On the other hand, we can replace async/await with
Then some people may wonder how we can compile generator into ES5. There is no easy-to-go correspondent in ES5 syntax, but there is still an intuitive way to keep a function’s context alive. As well-known, our good old friend, the closure. Generator can be represented with closure and
switchstatement in ES5. Now you may easily imagine how it’s done.
That’s it by me this time. If you have some more interesting knowledge on async/await, please let me know 😄