await setTimeout in async functions
Andrea Giammarchi
andrea.giammarchi at gmail.com
Tue Feb 28 19:47:03 UTC 2017
Why not using fill setTimeout API, also granting you args are those passed
at the invocation time and no possible mutation capable of affecting `
computeResult` could happen later on?
```js
const asyncFunc = (...args) => new Promise((resolve) => {
setTimeout(resolve, 1000, computeResult(...args));
});
```
Otherwise you can always do the following
```js
const asyncFunc = (...args) =>
new Promise(r => setTimeout(r, 1000))
.then(() => computeResult(...args));
```
isn't it?
On Tue, Feb 28, 2017 at 4:40 PM, Jérémy Judéaux <jeremy.judeaux at volune.net>
wrote:
> 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.
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170228/f8f90b6b/attachment-0001.html>
More information about the es-discuss
mailing list