await setTimeout in async functions

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


Let's take a simple asynchronous function
```js
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:
```js
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.

  *   https://esdiscuss.org/topic/promise-returning-delay-function
  *   https://esdiscuss.org/topic/a-promise-that-resolves-after-a-delay
Also IMO it would be easy to forget the `await` keyword.

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


Regards.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170228/298d969d/attachment.html>


More information about the es-discuss mailing list