在用async/await
時(shí),我遇到了一個(gè)錯(cuò)誤:
(node:7340) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: 全完了
(node:7340) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
錯(cuò)誤代碼如下:
function hh(bool) {
return new Promise((resolve,reject)=>{
setTimeout(function () {
if(bool) {
resolve("ok");
} else {
reject(new Error("全完了"));
}
},1000)
})
}
async function test(bool) {
return await hh(bool);
}
console.log(test(false));
而且返回test函數(shù)的處理結(jié)果是一個(gè)promise
對(duì)象褪秀,而不是預(yù)期的字符串或錯(cuò)誤對(duì)象三幻。后來(lái)查詢(xún)了相關(guān)資料碍侦,才明白標(biāo)注了async
的函數(shù)會(huì)成為一個(gè)異步函數(shù)邢隧,返回promise
對(duì)象店印。而且對(duì)于promise對(duì)象拋出的錯(cuò)誤是要處理一下的,不然就會(huì)報(bào)上面的錯(cuò)誤倒慧,修改后結(jié)果如下:
function hh(bool) {
return new Promise((resolve,reject)=>{
setTimeout(function () {
if(bool) {
resolve("ok");
} else {
reject(new Error("全完了"));
}
},1000)
})
}
async function test(bool) {
try {
console.log(await hh(bool));
} catch(err) {
console.error(err)
}
}
test(false);
現(xiàn)在就很正常了