[英]How can I use await in the NodeJs terminal?
我經常啟動 Node Js 終端來運行小任務或檢查一些數據。 當前的限制是我不能等待異步函數:
mymachine$ node
> const request = require('request-promise-native')
undefined
> await request('https://google.com')
Thrown:
await request('https://google.com')
^^^^^
SyntaxError: await is only valid in async function
我最終不得不做這樣的事情
> let data;
undefined
> request('https://google.com').then(x => data = x)
Promise { <pending> }
> data.length
46262
但這有一些不便之處。 有沒有其他選擇,以便我可以在節點終端中鏈接一系列await
命令?
以下是在啟動 REPL 時無需聲明即可執行此操作的方法
function testAsync() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("This executed after 2 sec");
}, 2000);
});
}
let result;
(async function() {
result = await testAsync();
console.log(result);
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.