javascriptasync-awaitv8javascript-engine

The mechanism for transforming JavaScript syntactic sugar in V8 using async/await as an example


Is syntactic sugar such as async/await converted before compilation/interpretation? Attention. I mean the situation when the engine supports the syntax of our code and we do not need to transpile it. I consider the issue in isolation from transpilation.

The neuron provides information that before the compilation/interpretation process there is a transformation that converts syntactic sugar into simpler structures.

Example:

const testFunction = async () => {
  let testPromise = new Promise((resolve, reject) =>
    setTimeout(() => {
      resolve('testResolve');
    }, 1110)
  );

  let result = await testPromise;
  console.log('Проверка');
  console.log('result', result);
};

testFunction();

Will it be converted into something similar before compilation?

const testFunction = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('testResolve');
        }, 1110);
    })
    .then(result => {
        console.log('Проверка');
        console.log('result', result);
    })
};

I tried to use google in many variants of queries but no info about transformation syntactic sugar


Solution

  • (V8 developer here.)

    There isn't a single mechanism, it depends.

    Some things are desugared right in the parser.
    Some things are desugared during bytecode creation.
    Some things that could perhaps be desugared have direct support instead, typically for performance reasons.

    For await specifically, see the bytecode generator and the intrinsic function it calls. So while there is some desugaring involved there, it's not what you sketched in your question.

    Note that these are implementation details that can and do change over time. So when you have a concrete need to know, go read the current source; don't rely on possibly-outdated years-old statements (like this answer will become soon enough ☺).