我在blog of version 14.3 release中读到,该版本支持“顶级等待”。这是否意味着该代码必须有效,如果没有,[支持顶层等待]的含义是什么
let x = 0
let myFunc = () => {
setTimeout(() => {
x = 2
}, 1000)
return x
}
let y = await myFunc()
console.log(y)
因为它在我更新的节点环境中不起作用
答案 0 :(得分:1)
是的,确实,Node.js现在已经支持顶级等待,尽管该语言尚未完全实现stage 3。您可以使用x <- read.table(header=TRUE, text=" Sex Height
1 Male 75
2 Male 70
3 Male 68
4 Male 74
5 Male 61
6 Female 65")
标志
--harmony-top-level-await
node --harmony-top-level-await ./beer.js
您可能仍然会收到以下错误;
async function beer(){
return "?"
}
const result = await test();
console.log(result); // "?"
要解决此问题,您需要告诉节点您的脚本属于模块类型。您可以通过以下两种方法来实现;
将package.json SyntaxError: await is only valid in an async function
设置为type
module
{
"main": "beer.js",
"type": "module"
}
或更改为node --harmony-top-level-await ./beer.js
扩展名.mjs
./beer.js => ./beer.mjs
答案 1 :(得分:0)
是的,正如@DanStarns在回答中所说的那样,
我尝试实现此示例,
import axios from 'axios';
const response = await axios('https://quote-garden.herokuapp.com/api/v2/quotes/random');
console.log(response.data);
package.json
{
"name": "async-await-top",
"version": "1.0.0",
"description": "",
"main": "top-level-async-await.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.19.2"
}
}
带有标志运行
node --harmony-top-level-await top-level-async-await.js
输出
G:\async-await-top>node --harmony-top-level-await top-level-async-await.js
{
statusCode: 200,
quote: {
_id: '5eb17aaeb69dc744b4e72b82',
quoteText: 'I can take more punishment than anyone in the business.',
quoteAuthor: 'Ric Flair',
quoteGenre: 'business',
__v: 0
}
}