0

I have been using axios to make API calls using the following pattern:

axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

In a codebase I am working on, the pattern for API calls looks like this:

export async function getUser(...) { 
   return new Promise((resolve, reject) => {
      customAxios.get("...", { params })
      .then(response => ....).then(resolve).catch(reject))
      .catch(error => 
         return new reject(...));
  });
}

Where customAxios looks like:

const customAxios = axios.create({...});
customAxios.interceptors.response.use(.....);

I haven't used Promises before, but what is the point of wrapping the axios call in a promise as oppose to style the axios documention has?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • There's no point. As posted it's actively _un_ helpful because you don't appear to be resolving the promise anywhere, so `await getUser(...)` would block forever. – jonrsharpe Apr 22 '22 at 14:45
  • 1
    @T.J.Crowder updated my snippet sorry. – Blankman Apr 22 '22 at 15:27
  • @Blankman - Yeah, you're right to be suspicious of that code. :-) It's got several issues: 1. The whole explicit promise creation thing. 2. Using `async` on a function that never uses `await` is pointless. 3. The second `.catch`'s callback will never be reached, because the first `.catch` callback converts rejection (of that promise) into fulfillment with `undefined`...which is good, because 4. `reject` is not a constructor function, so `new reject` would fail with `reject is not a constructor`. ... – T.J. Crowder Apr 22 '22 at 15:38
  • ... It should be just `const getUser = (/*...*/) => customAxios.get(/*...*/).then(({data}) => data);` or if you didn't want to expose the raw error to the caller: ```const getUser = (/*...*/) => customAxios.get(/*...*/).then(({data}) => data).catch(error => { /*...report `error`'...*/ throw new Error("Couldn't get user"); } );``` – T.J. Crowder Apr 22 '22 at 15:39

0 Answers0