javascript - 如何用async/await重构这个函数?

标签 javascript node.js async-await

我对 async/await 很陌生,想知道用 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);
      });
  }
}

当只向 .then 提供一个参数时,这对我来说非常简单,但如果您像这里那样有两个参数会怎样?

最佳答案

这是使用 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function 的方法作为引用:

 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);
        }         
    };
 }

关于javascript - 如何用async/await重构这个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46760295/

相关文章:

php - 使用 php 和 javascript 从 kml 文件创建高程图

javascript - d3.tree => 转换似乎不起作用

javascript - Websocket - 浏览器 websocket 没有从服务器接收消息

javascript - 将 Promise 转换为异步等待

javascript - 等待功能但仍然没有结果

asynchronous - Rust中异步/等待的目的是什么?

JavaScript - 有条件地抛出未捕获的语法错误

javascript - PHP 通过电子邮件将选定的变量发送给用户

mysql - nodejs mysql多个where查询

javascript - Express Server 似乎给 200 然后根据 post 请求给 404