As I understand it, as currently specified, the first part of an async
function, before the first await statement, is executed synchronously.

This is subject to subtle bugs when used with callbacks, which may be
common with DOM event handlers. Take the following code example:

```js
let someCondition = false;

async function onClick(event) {
  if (someCondition) {
    await Promise.resolve(); // Or any other async function.
  }
  event.stopPropagation();
}

let called = false;
onClick({ stopPropagation: () => called = true }).catch(console.error);
console.log("Called:", called);
```

The callback is called synchronously or not based on someCondition.

The behavior would be more consistent if the first part of the function
was scheduled at the next microtask, in other words it would be like
having an implicit `await Promise.resolve();` at the beginning of every
async function.

This would not allow async functions to invoke callbacks for DOM events
at all, without wrapping them in a normal function. Using an async
function as an event handler directly wouldn't be a good practice
anyways, because if the async function throws an exception it would
lead to an unhandled rejection, as if the `.catch()` in the example above was missing.

Is the current scheduling a deliberate choice?

I'm asking because async functions have just been implemented in the
Mozilla JS engine, and it would be good to know that this is what we
want before async functions get widespread use in our codebase.

Cheers,
Paolo
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to