folktale
folktale copied to clipboard
SyntaxError: await is only valid in async function
Running example code from task api doc throw the error: SyntaxError: await is only valid in async function
Steps to reproduce
Just running the following example code:
const { task } = require('folktale/concurrency/task');
const delay = (time) => task(
(resolver) => {
const timerId = setTimeout(() => resolver.resolve(time), time);
resolver.cleanup(() => {
clearTimeout(timerId);
});
resolver.onCancelled(() => {
/* does nothing */
});
}
);
const result = await delay(100).run().promise();
Expected behaviour
Should be run without any error.
Environment
(Describe the environment where the problem happens. This usually includes:
- OS: macos
- JavaScript VM
- Folktale version : 2.3.2 )
Additional information
node v8.12.0
This is indeed confusing :>
Most examples in the Folktale documentation are executed as a part of the automated testing phase. This guarantees that the examples we're putting there actually work when people try to execute them. But asynchronous code is a problem: it's hard to write it in a way that is more-or-less readable for developers. async/await makes that more palatable.
For now, await can only be used inside async functions. There's a proposal to allow it outside of functions as well (https://github.com/tc39/proposal-top-level-await), but that hasn't been implemented yet. This is not very nice for Folktale's docs because code examples aren't generally supposed to provide a function, they're meant to show you how to use an API. So, when running these examples, the test runner just wraps them in an async function, so these top-level await things work.
But if you copy the code as-is and throw it in the REPL or on your own file, it most likely won't. And the error message likely won't be that helpful :')
I'm not really sure how this should be fixed. I suppose a notice could be added on top of each example that does this explaining that top-level await isn't implemented in JS yet.
node --experimental-repl-await
https://nodejs.org/api/cli.html#cli_experimental_repl_await