¿在nodeJS中使用.catch((err)=>{})
实现承诺错误处理程序async/await
的最佳做法是什么?
代码在 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);
})
控制台输出表示未处理的承诺拒绝。
非常欢迎任何指向正确方向的指针,以及反模式中的更正或代码中的错误做法。
提前感谢您的时间和兴趣。
解决
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);
})
答案 0 :(得分:1)
查看您的代码,不确定您要执行的操作。 如果它创建两个承诺,然后随机拒绝或解决,。
以下是您修改后的代码 - >
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);
})
答案 1 :(得分:0)
在第二个示例中,您应抛出异常而不是尝试拒绝承诺。
async function asyncFnc2(){
try{
var res1 = await promise1;
var res2 = await promise2;
return res1 + ' ' +res2;
}catch(e){
throw new Error(e);
}
}