Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!