NodeJS script with async/await causing syntax error (v7.10.0)

前端 未结 1 637
南笙
南笙 2020-12-11 01:06

I am trying to use async/await in NodeJS but my script is throwing a syntax error.

I was under the impression that async/await is supported naively since Node 7.6. W

相关标签:
1条回答
  • 2020-12-11 01:33

    await is only valid inside async functions, so you need, for example, an async IIFE to wrap your code with:

    void async function() {
      let value = await getValueAsync();
      console.log(value);
    }();
    

    And, since return values from async functions are wrapped by a promise, you can shorten getValueAsync to simply this:

    async function getValueAsync() {
      return 'foo';
    }
    

    Or don't mark it as async and return a promise from it:

    function getValueAsync() {
      return new Promise(function(resolve) {
        resolve('foo');
      });
    }
    
    0 讨论(0)
提交回复
热议问题