Using await outside of an async function

前端 未结 5 553
野性不改
野性不改 2020-11-27 15:26

I was attempting to chain two async functions together, because the first had a conditional return parameter that caused the second to either run, or exit the module. Howeve

5条回答
  •  无人及你
    2020-11-27 15:49

    Top level await is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.

    There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:

    // data.js
    const data = await fetch( '/data.json' );
    export default data;
    

    Now any file that imports data.js won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.

    My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.

提交回复
热议问题