【问题标题】:How to refactor this function with async/await?如何用 async/await 重构这个函数?
【发布时间】:2018-03-27 09:11:52
【问题描述】:

我对 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 只提供一个参数时,这对我来说非常简单,但是如果你有两个像这里这样的参数会发生什么?

【问题讨论】:

  • await 无法提高清晰度时,您可能只想not change it at all
  • 这里的另一个问题是该函数不返回任何内容,因此调用者无法知道axios.post() 何时完成和/或是否有错误。您应该返回承诺,并且您的拒绝处理程序也需要传播错误,并且您的成功处理程序需要返回值。

标签: javascript node.js async-await


【解决方案1】:

.then 的两个参数只是成功和错误回调。你也可以写成.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

【讨论】:

  • 不,你真的不能,有一个difference between .then(…, …) and .then(…).catch(…) 可能很重要。
  • @Bergi 感谢您指出这一点。在这种特定情况下,我认为这无关紧要,因为 console.log 不会失败,但了解这种区别很重要。
  • 我不太确定。当它写入的标准输出流出现问题时,它可能会抛出?也许有人甚至弄乱了console 全局对象?或者一个不太人为的例子(我实际上在野外看到过)将是res 字符串化的一个例外。
  • axios.post(...)调用之前添加await,因为目前你的例子是绝对错误的。
  • @alexmac 谢谢我错过了最重要的部分!
【解决方案2】:

这里是如何做到这一点,使用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);
        }         
    };
 }

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2020-09-23
    相关资源
    最近更新 更多