无法让异步函数在简单的 NodeJS 脚本中工作

jBo*_*ive 2 javascript node.js async-await

所以,这里是 NodeJS 新手 - 请保持温和。;)

下面的代码在现代浏览器中运行良好:

async function testAsync(){
    return await new Promise(function(resolve){
        setTimeout(function(){
            resolve('Hello World!');
        }, 1000)

    })
}

const test = await testAsync();
console.log(test);
Run Code Online (Sandbox Code Playgroud)

它等待 1000 毫秒,直到打印“Hello World!” 到控制台,正如预期的那样。

使用我得到的相同代码运行 Node 10.3.0:

SyntaxError: await is only valid in async function
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

谢谢!

Cer*_*nce 7

你不能await在顶级(还),因为你试图做的await testAsync();。相反,使用.then

testAsync()
  .then(test => console.log(test));
Run Code Online (Sandbox Code Playgroud)

此外,拥有一个立即async返回awaited Promise的函数也没有多大意义。相反,只需返回 Promise:

testAsync()
  .then(test => console.log(test));
Run Code Online (Sandbox Code Playgroud)