doctopus
doctopus

Reputation: 5647

How to refactor this function with async/await?

I'm quite new to async/await and would like to know, what is the best way to refactor the below code with async/await?

export const createUser = (values, history) => {
  return dispatch => {
    axios.post('/api/signup', values)
      .then(res => {
        console.log('result', res);
      }, rej => {
        console.log('rejection', rej);
      });
  }
}

When only one argument is provided to .then it is pretty straightforward to me, but what happens if you have two arguments like here instead?

Upvotes: 5

Views: 1662

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191729

The two arguments to .then are just the success and error callbacks. You could also write this as .then(res => {}).catch(rej => {})

Essentially you can think of the result of await as a .then callback. Any time you're waiting for the result of a promise, whether or not you use it, use await. For any errors, use the usual try/catch.

return async () => {
  try {
    const res = await axios.post('/api/signup', values);
    console.log('result', res);
  }
  catch (rej) {
    console.log('rejection', rej);
  }
}

One thing to keep in mind is that async functions always return a Promise, so the calling code has to be written to account for that.

I wrote a blog post about async/await (disclaimer, yes I wrote this).1

Upvotes: 3

Duncan Thacker
Duncan Thacker

Reputation: 5188

Here's how to do it, using https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function as a reference:

 const f = (values, history) => {
    return async function createUser( dispatch ) {
        try {
           const res = await axios.post('/api/signup', values);
           console.log('result', res);
        } catch(e) {
           console.log('reject', e);
        }         
    };
 }

Upvotes: 4

Related Questions