0

I'm currently reading a post on Axios in React and I'm having trouble understanding Promises.

From my understanding, Axios is a promise-based library. But the code that I'm looking at is wrapping an Axios call in a new promise. Doesn't this double up on code?

I have a 'helpers' file in my react project with a login function and the code from the post is as follows;

return new Promise((resolve, reject) => {

    axios.post(baseUrl + 'login', formData, {
        headers: {
            Accept: 'application/json'
        }
    })
        .then(response => {
            const token = response.data.access_token;

            localStorage.setItem('access_token', token);

            resolve(response);
        })
        .catch(error => {
            console.log(error);

            reject(error);
        })

})

Isn't the then and catch the same as resolve and reject

Any help understanding this would be greatly appreciated.

Raj
  • 21
  • 8
CodeSauce
  • 255
  • 3
  • 19
  • 39
  • since axios seems to return a Promise already, this appears to be a common Promise anti-pattern - don't do it – Jaromanda X Sep 08 '19 at 03:02
  • 2
    the code you've written is equivalent of `return axios.post(...).then(response => { const token = response.data.access_token; localStorage.setItem('access_token', token); return response; }) .catch(error => { console.log(error); throw error; })` - do it that way (I've removed the axios post arguments for brevity) – Jaromanda X Sep 08 '19 at 03:09
  • I agree that wrapping this in a new promise seems unnecessary/redundant. Removing the extra promise and replacing `resolve(response)` with `return response`, and `reject(error)` with `throw error` gets you the same thing without the extra overhead. – ray Sep 08 '19 at 03:17
  • @JaromandaX ... If i do that, in my main file when calling the login function and adding `login(data) .then(response => { console.log(response); });` I get `undefined` .. Shouldnt that return the response? – CodeSauce Sep 08 '19 at 03:25
  • "*But the code that im looking at is wrapping a Axios call in a new promise.*" - then it is is horrible code. Stop reading that article. – Bergi Sep 08 '19 at 03:41
  • @CodeSauce - then you're doing something else wrong - perhaps you didn't read my suggestion correctly and forgot to return anything – Jaromanda X Sep 08 '19 at 06:49

0 Answers0