Home > OS >  How to chain a promise wrapper around axios.request
How to chain a promise wrapper around axios.request

Time:08-16

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

CodePudding user response:

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;
})

CodePudding user response:

You can let axios handle the status:

const axiosInstance = axios.create({
    validateStatus: function (status) {
        return status === 200;
    }
});

Axios requests in that instance will only resolve on status === 200. Default is status >= 200 && status < 300. All other status codes will make the promise reject.

  • Related