Redux 异步操作:将初始分派放入 try 块有什么不同吗?

Redux async actions: Does it make any difference to put initial dispatch into the try block?

考虑一下我正在使用 redux 异步操作进行非常通用的 api 调用。关于结果,有一个 "INIT" 调度和 "SUCCESS""FAILURE"

"INIT" 分派放入 try catch 块有什么不同吗?

选项 A(在 try catch 块之外):

export const doSomething = data => async dispatch => {
  dispatch(doSomethingInit()) // <-- outside try block
  try {
    let response = await client.get("/api")
    if (response) {
      dispatch(doSomethingSuccess(response.data))
    }
  } catch (error) {
    dispatch(doSomethingFailure(error))
  }
}

选项 B(在 try catch 块内):

export const doSomething = data => async dispatch => {
  try {
    dispatch(doSomethingInit()) // <-- inside the try block
    let response = await client.get("/api")
    if (response) {
      dispatch(doSomethingSuccess(response.data))
    }
  } catch (error) {
    dispatch(doSomethingFailure(error))
  }
}

我会说这只是一个微妙的无关紧要的细节,但是几乎每次我写一个新的异步操作时,我都会花一分钟时间思考它……:/

我通常避免认为事情不会throw

如果抛出怎么办?什么代码会处理它?您可能有一个外部 try-catch 块,但现在 doSomething 期间发生的事情正在其他地方处理。

我认为既然你的function/thunk正在“尝试”doSomething,它应该负责尝试捕捉 在其生命周期中可能发生的任何事情。即使在理论上,它不会在那个时候发生。

所以我通常选择选项B

export const doSomething = data => async dispatch => {
  try {
    dispatch(doSomethingInit()) // <-- inside the try block
    let response = await client.get("/api")
    if (response) {
      dispatch(doSomethingSuccess(response.data))
    }
  } catch (error) {
    console.error(error);                   // YOU MIGHT LOG IT HERE
    dispatch(doSomethingFailure(error))
  }
}

我还认为代码在 try-catch 块内的所有内容都更好读。