本文介绍了带有async/await的NodeJS脚本导致语法错误(v7.10.0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的印象是async/await被天真地支持自Node 7.6起.当我运行node -v时,我会得到v7.10.0.

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.

这是index.js的内容:

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

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

但是当我用node index.js调用此脚本时,我得到:

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

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.

I am running Linux Mint 18.1.

如何使我的脚本编译并运行?

How can I get my script to compile and run?

推荐答案

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

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

而且,由于async函数的返回值由Promise包裹,因此您可以将getValueAsync简化为以下形式:

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

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

或者不要将其标记为async并从中返回承诺:

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

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

这篇关于带有async/await的NodeJS脚本导致语法错误(v7.10.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 02:34