Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 298
doctopus Avatar asked Oct 15 '17 21:10

doctopus


People also ask

Can you await a async function?

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.

Can you await a function that returns a promise?

async and awaitInside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Can we replace promise with async await?

then() Promises and async/await are interchangeable. Whenever you see an await -statement, you can replace it with a . then() .


2 Answers

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);
        }         
    };
 }
like image 199
Duncan Thacker Avatar answered Nov 01 '22 08:11

Duncan Thacker


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

like image 23
Explosion Pills Avatar answered Nov 01 '22 06:11

Explosion Pills