¿What is the best practice to implement a promise error handler .catch((err)=>{})
using async/await
in nodeJS?
The code was run in nodeJS V8.10.0
Here are my unsuccessful attempts to implement the latter.
Consider the following code:
USING .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);
})
The console output is indicating an unhandled promise rejection.
Any pointers in the right direction are extremely welcome, as well as corrections in antipatterns or bad practices in the code.
Thanks in advance for your time and interest.
RESOLUTION
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);
})