Using Promise.reject() in async/await catch handler

Viewed 3143

I just wanted to know if it's a good practice to use the following code:

   const myFun = async () => {
     try {
         const response = await api();
         if(response.status === 200) {
            return response.data;
         }
      } catch(err) {
         return Promise.reject(err);
      }
   }

Here myFun will return a resolved/reject Promise that will be caught by another function. I just wanted to know if this is right way or are there any alternatives?

2 Answers

What you are doing is mixing async/await and Promises. You can just throw the err from inside the catch block.

const myFun = async () => {
     try {
         const response = await api();
         if(response.status === 200) {
            return response.data;
         }
      } catch(err) {
         throw err;
      }
   }

After this you can catch the error wherever you call myFun.

The end result in both cases would be the same. The only difference is that throw can be used anywhere in JS code but Promise.reject can only be called from within an asynchronous code block only

You are achieving nothing by trying to re-throw the error from api().

Using async function will cause Promise.reject(error) to be called implicitly when an error is thrown anyway.

Just write your function like this:

const myFun = async () => {
     const response = await api();
     if (response.status === 200) {
          return response.data;
     }
     // You might want to return something else here
}

Then the calling function will still receive the error:

try {
    await myFun();
} catch (error) {
    // error still received
}
Related