在位于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
语法而不是"然后"语法,如果出现问题,我将如何获取错误对象?
e.g。
let response = await fetch(`https://www.reddit.com/r/${subreddit}.json`)
let json = await response.json();
我可以使用try/catch
包围这些代码行,但作者有一个严厉的警告,不要在这里使用catch(请参阅上面的代码段)。
有没有一种方法可以将async/await
模式与此代码一起使用?
答案 0 :(得分:1)
在您提供的链接中,请注意避免使用catch
关于promise .catch
语句。这是因为它会捕获then
块中的错误。而不仅仅是通过fetch
或response.json()
导致的错误,它还会捕获由dispatch(receivePosts(subreddit, json))
您应该能够使用您在帖子中描述的异步等待,同时避免捕获由dispatch
引起的错误。 e.g。
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));
}
}
}