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

156
Visualizações
How to chain a promise wrapper around axios.request

I've this quick doubt that might be related to promise chaining but I'm not able to think about it clearly.

So basically, I've this function(myFn) that returns axios.request() which basically returns a promise, so i can now do myFn.then().catch() and it works, now what I want to do is to create a promise wrapper on top of that, which will resolve only when response.data.status =="somevalue", here response.data means the request was successful and a result came but now i want to resolve myFn only when response.data.status =="somevalue".

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Since your function returns a promise, you can just use the promise's result in the .then callback. If the response.data.status isn't what you want, throw an error, otherwise return the response, thus resolving the promise:

myFn().then(response => {
  if (response.data.status !== "somevalue") {
    throw new Error("invalid status");
  }
  return response;
})

Edit: If you want to wrap this in a custom Promise, you could do something like this:

const myPromise = new Promise((resolve, reject)=>{
    myFn().then(response => {
    if (response.data.status !== "somevalue") {
        reject("Invalid status");}
    else{
        resolve("somevalue");}
    });
});

And then call this promise with callback functions for the fulfilled and rejected cases of the promise:

myPromise.then(handleSucess, handleFailure);

For reference see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

about 4 years ago · Santiago Trujillo Relatório

0

You can try if this works for you. I am not sure though, if the throw here works as expected.

const axiosInstance = axios.create({
    transformResponse: [function (data) {
        if (data.status === "somevalue") {
            return data;
        }
        throw new Error(`wrong status: ${data.status}`);
    }],
});

Then use this axiosInstance to do your calls.

If this does not work, you could also give the axios response interceptors a try. How can you use axios interceptors.

about 4 years ago · Santiago Trujillo 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