Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly handle reject in Promises

We have this function in our code that is used to log in a user

const userLogin = loginData => {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await auth.post("/login", loginData);
      resolve(res);
    } catch (error) {
      reject(error);
    }
  });
};
// Calling function
const loginSubmit = async values => {
  try {
    const res = await userLogin(values);
    console.info(res);
  } catch (error) {
    console.error("Catch: ", error);
  }
};

But from this stackoverflow answer, try-catch blocks are redundant in Promises. I wanted to try and clean this code, so I changed the code above into:

const userLogin = loginData => {
  return new Promise(async (resolve, reject) => {
    const res = await auth.post("/login", loginData);
    if (res.status !== 201) {
      reject(new Error("Error"));
    }
    resolve(res);
  });
};

However, when I tried to login with incorrect credentials, the console logs an Uncaught (in promise) Error: Request failed with status code 400

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m not really familiar with creating my own promises, so I don’t know how to do this properly.

>Solution :

Couple of problems in your code:

  • You are unnecessarily creating a promise; auth.post(..) already returns a promise, so you don’t need to create a promise yourself and wrap auth.post(...) inside a promise constructor.

  • Another problem in your code is that executor function (function passed to the promise constructor) is marked as async; it should not be an async function.

Your function could be re-written as:

const userLogin = async (loginData) => {
    const res = await auth.post("/login", loginData);
    
    if (res.status !== 201) {
      throw new Error("Error"));
    }

    return res;
};

You could also re-write your function as:

const userLogin = async (loginData) => {
    return auth.post("/login", loginData);       
};

Don’t forget to use the catch in the code that calls this function.

You might want to read the following article to understand whether you need the try-catch block: await vs return vs return await

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading