3 回答

TA貢獻1851條經(jīng)驗 獲得超5個贊
多虧了其他評論者和一些其他研究await只能用于一個async功能,例如
async function x() {
var obj = await new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({a:42});
},100);
});
return obj;
}
然后,我可以將此功能用作Promise,例如
x().then(console.log)
或在另一個異步功能中。
令人困惑的是,Node.js副本不允許您執(zhí)行
await x();
與RunKit筆記本環(huán)境一樣。

TA貢獻1827條經(jīng)驗 獲得超9個贊
正如其他人所說,您不能在異步函數(shù)之外調用“ await”。但是,要解決此問題,可以包裝await x();。在異步函數(shù)調用中。即
function x() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({a:42});
},100);
});
}
//Shorter Version of x():
var x = () => new Promise((res,rej)=>setTimeout(() => res({a:42}),100));
(async ()=>{
try{
var result = await x();
console.log(result);
}catch(e){
console.log(e)
}
})();
這應該在Node 7.5或更高版本中工作。也適用于鉻金絲雀片段。

TA貢獻1878條經(jīng)驗 獲得超4個贊
因此,根據(jù)其他人的建議,await可以在異步內部運行。因此,您可以使用以下代碼來避免使用then:
async function callX() {
let x_value = await x();
console.log(x_value);
}
callX();
添加回答
舉報