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

128
Vistas
How to resolve or reject a promise from the result of another promise?

Really sorry if this has been answered, I've searched everywhere and can't find the exact problem I'm facing.

Take this as the example:

const fetchData = (email, password) => new Promise(async (resolve, reject) => {
    await axios.post('https://api.something.com', {
            email: email,
            password: password,
        },
        {            
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(res => {  
            cookie = res.headers['set-cookie'];
        })
        .catch(err => {
            return reject('Login failed');  
        });

    await axios.get('https://api.something.com', {
            headers: {
                'cookie': cookie
            }
        })
        .then(res => {  
            data = res;
        })
        .catch(err => {
            return reject('Failed to retrieve something'); 
        });    

    return resolve(data);
});

If the login credentials are incorrect, the 'Login failed' reject is sent but the script will keep on running and there will be an additional error message saying that cookie isn't set. I want to completely stop the script in the first catch.

I could use throw new Error('Login failed') and that would stop the script completely but I don't feel like that's the right answer and also because it makes me wonder what else could I use to resolve the promise (for other purposes) and still don't let the script continue running.

I'm also not interested in nesting functions, to avoid promise-callback christmas tree-like hell.

Am I making sense?

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

0

Because you use async/await you don't need create a new Promise and instead of then/catch use await and try/catch;

const fetchData = async (email, password) => {
  let cookie;
  try {
    const res = await axios.post(
      "https://api.something.com",
      {
        email,
        password
      },
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );
    cookie = res.headers["set-cookie"];
  } catch (err) {
    throw new Error("Login failed");
  }

  let data;
  try {
    const res = await axios.get("https://api.something.com", {
      headers: {
        cookie
      },
    });
    data = res;
  } catch (err) {
    throw new Error("Failed to retrieve something");
  }

  return data;
};

If you want to use the Promise API instead of async/await you can chanin the promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining

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