【问题标题】:redux asynchronous action with await/async带有 await/async 的 redux 异步操作
【发布时间】:2018-02-15 11:48:27
【问题描述】:

从位于here 的教程中,我对这部分代码有疑问:

export function fetchPosts(subreddit) {
  // Thunk middleware knows how to handle functions.
  // It passes the dispatch method as an argument to the function,
  // thus making it able to dispatch actions itself.

  return function (dispatch) {
    // First dispatch: the app state is updated to inform
    // that the API call is starting.

    dispatch(requestPosts(subreddit))

    // The function called by the thunk middleware can return a value,
    // that is passed on as the return value of the dispatch method.

    // In this case, we return a promise to wait for.
    // This is not required by thunk middleware, but it is convenient for us.

    return fetch(`https://www.reddit.com/r/${subreddit}.json`)
      .then(
        response => response.json(),
        // Do not use catch, because that will also catch
        // any errors in the dispatch and resulting render,
        // causing an loop of 'Unexpected batch number' errors.
        // https://github.com/facebook/react/issues/6895
        error => console.log('An error occured.', error)
      )
      .then(json =>
        // We can dispatch many times!
        // Here, we update the app state with the results of the API call.

        dispatch(receivePosts(subreddit, json))
      )
  }
}

假设我想使用async/await 语法而不是“then”语法,如果出现故障,我将如何获取错误对象?

例如

let response = await fetch(`https://www.reddit.com/r/${subreddit}.json`)
let json = await response.json();

我可以用try/catch包围这些代码行,但是作者有一个严厉的警告,不要在这里使用catch(参考上面的sn-p)。

那么有没有合适的方法在这段代码中使用async/await 模式?

【问题讨论】:

    标签: asynchronous redux


    【解决方案1】:

    在您提供的链接中,避免使用catch 的注释是关于承诺.catch 声明的。这是因为它会在两个 then 块中捕获错误。它不仅可以捕获由fetchresponse.json() 引起的错误,还可以捕获由dispatch(receivePosts(subreddit, json)) 引起的错误

    您应该能够使用您在帖子中描述的异步等待,同时避免捕获由dispatch 引起的错误。例如

    export function fetchPosts(subreddit) {
      return async function (dispatch) {
        dispatch(requestPosts(subreddit));
        let response;
        let json;
        try {
          response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
          json = await response.json();
        }  catch(e) {
          // handle fetch or json error here e.g.
          dispatch(receivePostsError(subreddit, e.message));
        }
        if (json) {
          dispatch(receivePosts(subreddit, json));
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 2020-04-23
      • 2019-11-14
      • 2016-06-02
      • 1970-01-01
      • 2017-10-26
      相关资源
      最近更新 更多