【发布时间】:2016-11-23 08:42:19
【问题描述】:
当我从函数 A 向函数 B 返回一个 Promise 时,如何捕获错误,然后从 A 返回数据,并且两个调用都捕获 Promise?我知道,当 promise 被解决时,A 总是首先被执行,然后是 B,然后是从 A 返回的数据。但是当这种 Promise 的返回形成一条长链时,我无法理解如何捕获错误。这是场景的简化示例。我正在使用 Redux-thunk 动作创建者来管理状态。
function postActionCreator(data) {
return (dispatch) => {
dispatch(type: POST_LOADING)
return Source.post()
.then(response => {
dispatch(type: POST_SUCCESS, payload: response)
return response
})
.catch(error => {
// Is this catch called if handlePost throws error in then?
dispatch(type: POST_ERROR, payload: error)
throw new Error(error)
})
}
}
// Container component's post function calling the Redux action creator
function handlePost(data) {
this.props.postActionCreator(data)
.then(response => {
// Do something with response
})
.catch(error => {
// Or is the error caught with this catch?
})
}
// Or are the both catchs called, in which order and why?
这三种不同场景下的错误是如何处理的:
- Source.post 抛出和错误
- postActionCreator 会抛出错误
- handlePost 会引发错误
【问题讨论】:
-
1) 两个捕获,2) 两个捕获(尽管您发布的代码从未在其中抛出),3) handlePost 的捕获
标签: javascript exception asynchronous promise redux