Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda