Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
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

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think that in your case since you call to async function inside the constructor of the promise you need to use try catch.
The answer you referred is correct as long as the error happened while you are in the constructor (i.e. the Promise object is in the making), however in your case the rejection of the auth function happens long after the Promise was constructed and therefore it is not rejecting it.

BTW - You don't have to await in the promise. You may do the following:

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

Since you resolve the async auth call, any rejection by the auth call will be reflect as a rejection from you function

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda