Asynchronous 使用wait/async重新执行异步操作

Asynchronous 使用wait/async重新执行异步操作,asynchronous,redux,Asynchronous,Redux,在找到的教程中,我对代码的这一部分有一个问题: 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 fun

在找到的教程中,我对代码的这一部分有一个问题:

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”语法,如果出现故障,我将如何获取错误对象

e、 g

我可以用
try/catch
来包围这些代码行,但是作者有一个严厉的警告,不要在这里使用catch(请参阅上面的代码片段)


那么,有没有一种合适的方法可以将
async/await
模式用于此代码呢?

在您提供的链接中,避免使用
catch
的注意事项是关于promise
.catch
语句的。这是因为它将捕获
块中的错误。除了通过
fetch
response.json()
引起的错误,它还将捕获通过
dispatch(receivePosts(subreddit,json))引起的错误。

您应该能够使用async Wait,正如您在文章中所描述的那样,同时避免捕获由
调度引起的错误。e、 g

导出函数fetchPosts(subreddit){
返回异步函数(调度){
调度(请求发布(subreddit));
让我们回应;
让json;
试一试{
响应=等待获取(`https://www.reddit.com/r/${subreddit}.json`);
json=wait response.json();
}捕获(e){
//在此处处理fetch或json错误,例如。
发送(接收邮件(subreddit,e.message));
}
if(json){
发送(接收邮件(subreddit,json));
}
}
}
let response = await fetch(`https://www.reddit.com/r/${subreddit}.json`)
let json = await response.json();