Using await outside of an async function

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

    Even better is to put additional semicolon in front of the code block

    ;(async () => {
        await ...
    })();
    

    This prevents auto-formatter (e.g. in vscode) to move the first parenthese to the end of the previous line.

    The problem can be demonstrated on the following example:

    const add = x => y => x+y
    const increment = add(1)
    (async () => {
        await ...
    })();
    

    Without the semicolon, this will be re-formatted as:

    const add = x => y => x+y
    const increment = add(1)(async () => {
      await Promise(1)
    })()
    

    which obviously is wrong because it assigns the async function as the y parameter and tries to call a function from the result (which is actually a weird string '1async () => {...}')

提交回复
热议问题