Aman
Aman

Reputation: 81

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".

Upvotes: 0

Views: 955

Answers (2)

Braxton Little
Braxton Little

Reputation: 126

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

Upvotes: 3

HEllRZA
HEllRZA

Reputation: 274

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.

Upvotes: 1

Related Questions