How to reorganize this function using async / wait?

I am new to async / await and would like to know what is the best way to reorganize the code below using async / wait?

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

If .thenonly one argument is provided for me, it's pretty simple for me, but what happens if you have two arguments instead?

+4
source share
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);
        }         
    };
 }
+3
source

Two arguments .thenare only successful and callbacks. You can also write it as.then(res => {}).catch(rej => {})

, await .then. , , , await. try/catch.

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

, async Promise, .

async/await ( , , ). 1

+2

Source: https://habr.com/ru/post/1687525/


All Articles