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)
我错过了什么?
谢谢!
你不能await
在顶级(还),因为你试图做的await testAsync();
。相反,使用.then
:
testAsync()
.then(test => console.log(test));
Run Code Online (Sandbox Code Playgroud)
此外,拥有一个立即async
返回await
ed Promise的函数也没有多大意义。相反,只需返回 Promise:
testAsync()
.then(test => console.log(test));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4382 次 |
最近记录: |