0

¿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);
})

CONSOLE OUTPUT: enter image description here

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);
})
Jorge González
  • 2,898
  • 1
  • 9
  • 12
  • Possible duplicate of [How to reject in async/await syntax?](https://stackoverflow.com/questions/42453683/how-to-reject-in-async-await-syntax) – Andre Figueiredo Mar 25 '18 at 01:13
  • 1
    I think you have got yourself a little confused on how promises work,.. `var promise1 = new Promise((resolve,reject)=>{`, this is a promise, an it will execute immediately. You then have `async function asyncFnc2(){` that waits on `promise1` & `promise2`, that have already started, and the `promise3` is never even waited on. Normally when you create a new Promise, you invoke it from another function. eg.. `function test() { return new Promise(resolve, reject) {}}` etc. – Keith Mar 25 '18 at 01:31

2 Answers2

1

Looking at your code, not really sure what you trying to do. If it's create two promises, and then randomly reject or resolve,.

Below is your code modified to do this->

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);
})
Keith
  • 22,005
  • 2
  • 27
  • 44
  • Thanks Keith! You are absolutely right. You said: I think you have got yourself a little confused on how promises work,.. var promise1 = new Promise((resolve,reject)=>{, this is a promise, an it will execute immediately. You then have async function asyncFnc2(){ that waits on promise1 & promise2, that have already started, and the promise3 is never even waited on. Normally when you create a new Promise, you invoke it from another function. eg.. function test() { return new Promise(resolve, reject) {}} – Jorge González Mar 25 '18 at 01:47
0

In the second example you should throw the exception instead of trying to reject the promise.

async function asyncFnc2(){
    try{
          var res1 = await promise1;
          var res2 = await promise2;
          return res1 + ' ' +res2;
    }catch(e){
        throw new Error(e);
    }
}
Keith Rousseau
  • 4,435
  • 1
  • 22
  • 28