Redux thunk:从调度操作中返回承诺
Redux thunk: return promise from dispatched action
是否可以从操作创建者返回承诺/信号,当 Redux thunk 成功调度某些操作时解决?
请考虑此操作创建者:
function doPost(data) {
return (dispatch) => {
dispatch({type: POST_LOADING});
Source.doPost() // async http operation
.then(response => {
dispatch({type: POST_SUCCESS, payload: response})
})
.catch(errorMessage => {
dispatch({type: POST_ERROR, payload: errorMessage})
});
}
}
当 Redux 调度POST_SUCCESS或POST_ERROR操作时,我想在调用 doPost 操作创建器后在组件中异步调用某些函数。一种解决方案是将回调传递给操作创建者本身,但这会使代码变得混乱且难以掌握和维护。我也可以在 while 循环中轮询 Redux 状态,但效率低下。
理想情况下,解决方案将是一个承诺,当某些操作(在本例中为POST_SUCCESS或POST_ERROR)被调度时,它应该解决/拒绝。
handlerFunction {
doPost(data)
closeWindow()
}
上面的示例应该重构,因此 closeWindow() 只有在 doPost() 成功时才被调用。
当然,您可以从异步操作中返回承诺:
function doPost(data) {
return (dispatch) => {
dispatch({type: POST_LOADING});
// Returning promise.
return Source.doPost() // async http operation
.then(response => {
dispatch({type: POST_SUCCESS, payload: response})
// Returning response, to be able to handle it after dispatching async action.
return response;
})
.catch(errorMessage => {
dispatch({type: POST_ERROR, payload: errorMessage})
// Throwing an error, to be able handle errors later, in component.
throw new Error(errorMessage)
});
}
}
现在,dispatch
函数返回一个承诺:
handlerFunction {
dispatch(doPost(data))
// Now, we have access to `response` object, which we returned from promise in `doPost` action.
.then(response => {
// This function will be called when async action was succeeded.
closeWindow();
})
.catch(() => {
// This function will be called when async action was failed.
});
}
相关文章:
- 谷歌日历 api 调用可以在角度工厂内返回承诺吗?
- JavaScript - 返回承诺和/或调用回调
- 在同一函数中解析承诺后返回承诺
- 承诺返回承诺
- 承诺返回承诺
- 如何从多个承诺中返回承诺
- 如何使用在 AngularJS 中返回承诺的$resource测试工厂
- 这是一种常见的模式吗?(返回数据而不是返回承诺)
- 使用 Jasmine 2.4.* 测试返回承诺的服务
- 承诺回调返回承诺
- 可以 Angular 模板调用函数返回承诺
- 链接返回承诺数组的函数
- 使用属性从指令返回承诺
- 节点.js SQLite 3 返回承诺
- 从延迟的回调中返回承诺
- 返回承诺与返回承诺内未定义之间的区别
- 返回承诺值
- 如何在返回承诺的服务中创建 reset() 方法
- 从顺序 jQuery ajax 调用返回承诺
- 在 Redux Thunk 发货后从商店返回承诺