await setTimeout in async functions

Jérémy Judéaux jeremy.judeaux at
Tue Feb 28 16:40:01 UTC 2017

Let's take a simple asynchronous function
const asyncFunc = (...args) => new Promise((resolve) => {
  setTimeout(() => resolve(computeResult(...args)), 1000);

One problem in this example is that any error thrown by `computeResult` will not be correctly handled. This can be solved with an `async` function:
const delay = (duration) =>
  new Promise(resolve => setTimeout(resolve, duration));

const asyncFunc = async (...args) => {
  await delay(1000);
  return computeResult(...args);
It's always better to handle errors. So I would not be surprised if a similar pattern become favoured over the use of `setTimeout`, when writing and learning asynchronous functions.

Writing a `delay` function is easy. But a standardised statement (`await*delay`, `await.nextTick` or whatever name or syntax) would highlight these patterns. It would also be an opportunity to standardise `setTimeout`, `setImmediate` and such, without risking incompatibilities (I've seen that point reported in a recent email).
Cancellation would probably be a sensible point, but it may also be left to a more global solution about cancelling `async` functions.

I’ve found some old discussions about a Promise-returning delay function, showing that the (lack of?) concept of event-loop in ES would be a problem.

Also IMO it would be easy to forget the `await` keyword.

Is it worth discussing again, in the context of `async` functions?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list