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

标签 node.js async-await syntax-error

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

我的印象是 async/await 是 supported naively since Node 7.6 .当我运行 node -v 我得到 v7.10.0.

这里是index.js的内容:

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

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

但是当我用 node 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)

我正在运行 Linux Mint 18.1。

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

最佳答案

await 仅在 async 函数内部有效,因此您需要例如 async IIFE包装你的代码:

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

而且,由于 async 函数的返回值被一个 Promise 包装,您可以将 getValueAsync 简化为:

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

或者不要将其标记为 async 并从中返回一个 promise :

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

关于node.js - 带有 async/await 的 NodeJS 脚本导致语法错误(v7.10.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44098013/

相关文章:

node.js - 使用 Azure Easytables 和 Node.js 后端时出现 HTTP 500 错误

node.js - 尝试使用 Protocol Buffers - Google 的数据交换格式时,goog 未定义错误

javascript - 如果我在异步调用中省略 "await",操作是否仍会完成?

rust - 如何使用 Rust 中的 StreamExt::scan 方法改变异步 block 内的状态?

sql - Access 2013 : Why am I getting this Syntax Error?

javascript - 链接方法并将结果传递给 Javascript 中的下一个链接函数

javascript - NodeGit - 解决有利于 "theirs"的 merge 冲突

c# - 为什么后台线程不等待任务完成?

php - 语法错误,意外的“用户类型” <T_CONSTANT_ENCAPSED_STRING>

jQuery 未捕获类型错误 : Property '$' of Object is not a Function