gpt4 book ai didi

javascript - 如何使用 async/await 处理错误?

转载 作者:行者123 更新时间:2023-12-03 02:13:08 25 4
gpt4 key购买 nike

¿使用 async/await 实现 Promise 错误处理程序 .catch((err)=>{}) 的最佳实践是什么在nodeJS中?

代码在nodeJS V8.10.0

中运行

这是我实现后者的不成功尝试。

考虑以下代码:

使用 .catch((err)=>{})

    //Function that rejects a promise with a probability of 50%
function randomReject(resolve,reject){
setTimeout(()=>{
if(Math.random() > 0.5)
resolve('Bigger than 1/2');
else
reject('Smaller than 1/2');
},500)
}

//Test promises
//THESE PROMISES ARE DECLARED INCORRECTLY
var promise1 = new Promise((resolve,reject)=>{ //HERE IS THE PROBLEM
randomReject(resolve,reject);
})
var promise2 = new Promise((resolve,reject)=>{ //HERE IS THE PROBLEM
randomReject(resolve,reject);
})
//EXPLANATION: Without a wrapper function around the promises, these will
//run in place as soon as they are declared. And since there is no promise
//rejection handler declared in the latter code these will cause an
//"UnhandledPromiseRejectionWarning" in NodeJS.

//Async function declaration
async function asyncFnc2(){
var res1 = await promise1;
var res2 = await promise2;
return res1 + ' ' +res2;
}

//Async function call
asyncFnc2().then((val)=>{
console.log(val);
}).catch((err)=>{
console.log(err);
})

控制台输出: enter image description here

控制台输出指示未处理的 promise 拒绝。

非常欢迎任何正确方向的指针,以及代码中反模式或不良实践的更正。

预先感谢您的时间和兴趣。

解决方案

function randomReject(resolve,reject){
setTimeout(()=>{
if(Math.random() > 0.5)
resolve('Bigger than 1/2');
else
reject('Smaller than 1/2');
},500)
}

//Test promises
//These promises are wrapped around functions so they are not run in place
function promise1(){
return new Promise((resolve,reject)=>{
randomReject(resolve,reject);
})
}
function promise2(){
return new Promise((resolve,reject)=>{
randomReject(resolve,reject);
})
};
//These promises are wrapped around functions so they are not run in place

//No need for the "try catch", just let the async function do the dirty
//work.

async function asyncFnc2(){
var res1 = await promise1();
var res2 = await promise2();
return res1 + ' ' +res2;
}

//Any exception will be automatically catch by the ".catch((err)=>{})"
asyncFnc2().then((val)=>{
console.log(val);
}).catch((error)=>{
console.log(error);
})

最佳答案

看着你的代码,不太确定你想做什么。如果它创建两个 Promise,然后随机拒绝或解决。

下面是您修改后的代码来执行此操作->

function randomReject(){
return new Promise((resolve, reject) => {
setTimeout(()=>{
if(Math.random() > 0.5)
resolve('Bigger than 1/2');
else
reject('Smaller than 1/2');
},500)
});
}

async function asyncFnc2(){
var res1 = await randomReject();
var res2 = await randomReject();
return res1 + ' ' +res2;
}
asyncFnc2().then((val)=>{
console.log(val);
}).catch((error)=>{
console.log(error);
})

关于javascript - 如何使用 async/await 处理错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49471566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com