带有async / await的NodeJS脚本导致语法错误(v7.10.0)

时间:2021-01-21 22:43:41

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

我试图在NodeJS中使用async / await,但我的脚本抛出语法错误。

I was under the impression that async/await is supported naively since Node 7.6. When I run node -v I get v7.10.0.

我的印象是,自Node 7.6以来,async / await得到了天真的支持。当我运行节点-v时,我得到v7.10.0。

Here is the contents of index.js:

这是index.js的内容:

async function getValueAsync() {
    return new Promise(function(resolve) {
        resolve('foo');
    });
}

let value = await getValueAsync();
console.log(value);

But when I invoke this script with node index.js I get:

但是当我用节点index.js调用这个脚本时,我得到:

let value = await getValueAsync();
                  ^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)

I am running Linux Mint 18.1.

我正在运行Linux Mint 18.1。

How can I get my script to compile and run?

如何编译和运行我的脚本?

1 个解决方案

#1


9  

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

await仅在异步函数内有效,因此您需要使用异步IIFE来包装代码:

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:

并且,由于异步函数的返回值由promise包装,因此您可以将getValueAsync缩短为:

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');
  });
}

#1


9  

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

await仅在异步函数内有效,因此您需要使用异步IIFE来包装代码:

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:

并且,由于异步函数的返回值由promise包装,因此您可以将getValueAsync缩短为:

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');
  });
}