【发布时间】: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