Using await outside of an async function

前端 未结 5 544
野性不改
野性不改 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:34

    you can do top level await since typescript 3.8
    https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#-top-level-await
    From the post:
    This is because previously in JavaScript (along with most other languages with a similar feature), await was only allowed within the body of an async function. However, with top-level await, we can use await at the top level of a module.

    const response = await fetch("...");
    const greeting = await response.text();
    console.log(greeting);
    
    // Make sure we're a module
    export {};
    

    Note there’s a subtlety: top-level await only works at the top level of a module, and files are only considered modules when TypeScript finds an import or an export. In some basic cases, you might need to write out export {} as some boilerplate to make sure of this.

    Top level await may not work in all environments where you might expect at this point. Currently, you can only use top level await when the target compiler option is es2017 or above, and module is esnext or system. Support within several environments and bundlers may be limited or may require enabling experimental support.

提交回复
热议问题