Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SyntaxError: await is only valid in async function #218

Open
geohuz opened this issue May 2, 2019 · 2 comments
Open

SyntaxError: await is only valid in async function #218

geohuz opened this issue May 2, 2019 · 2 comments

Comments

@geohuz
Copy link

geohuz commented May 2, 2019

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

@robotlolita
Copy link
Member

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.

@imcotton
Copy link

node --experimental-repl-await

https://nodejs.org/api/cli.html#cli_experimental_repl_await

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants