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?
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.
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.
then() Promises and async/await are interchangeable. Whenever you see an await -statement, you can replace it with a . then() .
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);
}
};
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With