A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

[PROPOSAL] Let native-side APIs accept async functions

trusktr
2016-03-30

For example, what if we could do

document.querySelector('a#some-link').addEventListener(async function() {
  let result = await someThingThatWeNeed()

  // ... possibly show a loading icon, or something ...

  // Finally, abort default behavior depending on the result.
  if (!result) return false

  // otherwise the action continues as normal.
})

It might be possible to monkey-patch addEventListener to make a POC of this, as well as any other native places where behavior can depend on the result of a function passed to native code.

What are your thoughts and feedback on this idea?

AshleyScirra
2016-03-31

It is difficult to allow calls to things like preventDefault() in an async handler, because usually the browser needs to know synchronously if you will do that, e.g. so it knows not to scroll the page if you block a scroll event. But then maybe the new passive option for events could enable this…?

tabatkins
2016-03-31

Agreed that we can’t expose a lot of functionality to an async function, because it needs to tell the browser syncly about things. Passive listeners help since they also disable the ability to tell the browser about things from the event.

I don’t think one can tell from the function that something is async or not; all it does as far as the outside world is concerned is make it so that the function immediately returns a promise when called. So we can’t have the browser help out and throw when you use an async function in a non-passive listener accidentally. :confused:

One can use async functions fairly easily by themselves, tho:

el.addEventListener('click', function(e) {
 let p = (async function(e) { await somePromiseThing(); })(e);
 // do whatever sync things you want to do for the event here
});