Can async / await always be automatically replaced by Promises chains?

304 views Asked by At

Usually, Promises chains can be rewritten using async/await

   const f = () => Promise.resolve(1).then(a => a+1)

can be translated to

   const f = async () => {
       const a = await Promise.resolve(1)
       return a+1
    }

If I'm not wrong in Javascript async/await is implemented using coroutines (like generators).

So internally Javascript does not ever translate the async/await code to a promise chain code before execution (do not consider async/await a syntactic sugar).

Looking around I found a transpiler that asserts to change async/await to promises chain. Doing so is taking async/await as a syntactic sugar that is expanded before execution. And doing so states that is even more performant than coroutine implementation.

Now I'm wondering.

Can that transpiler always automatically rewrite every async/await code without any problem? Or there are cases where the transpilation can not automatically give the same result as the coroutine implementation?

Same question in another way. Why was chosen to use coroutine implementation and not transpile to the Promises chain? Because transpilation is not always possible?

1

There are 1 answers

0
vitaly-t On

The best solution for this nowadays is to write the code in TypeScript, with target set to ES5, then every await/async will always be correctly replaced with the corresponding Promise chain.