反应 Redux 异步操作在完成函数后调用下一个函数
react redux async action call next function after finishing the function
假设我有一个调用 api 的函数:
export default function AuthApi({url, method, headers, data}={}){
return (dispatch, getState) => {
fetch(url, {
method: method || null,
headers: headers || null,
body: form || null,
}).then(function(response) {
return response.json();
}).then(function(response){
console.log(response)
})
}
}
现在我想在某个地方调用这个 api:
dispatch(AuthApi({url: "some_url", method: "POST", data: data}))
console.log("called api")
dispatch(userInfo(response))
console.log(getState())
router.pushState(null, '/profile')
在这里,我用 dispatch
调用 api,然后dispatch(userInfo)
.我假设在 dispatch(AuthApi())
中的所有处理之后调用我的 dispatch(userInfo())
函数
但是在这里它进入AuthApi()
但没有完成它就开始调用其他函数或进程
我怎么能只调用我的其他函数或逻辑,或者在dispatch(AuthApi())
完全完成后console.log()
。
谢谢
您可以使用 Promises,它们与 thunkMiddleware
配合得很好:
dispatch(AuthApi({url: "some_url", method: "POST", data: data})).then((response) => {
dispatch(userInfo(response))
})
更多例子在这里
更新您还应该修改操作以返回承诺。
export default function AuthApi({url, method, headers, data}={}){
return (dispatch, getState) => {
return fetch(url, {
method: method || null,
headers: headers || null,
body: form || null,
}).then(function(response) {
return response.json();
})
}
}
相关文章:
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 在输入字段上有两个函数调用,一个在Blur上,一个不在Angular中
- 如何在Javascript函数调用中循环变量
- Javascript:应为赋值或函数调用,但实际看到的却是表达式
- 如何远程检查JavaScript应用程序的函数调用堆栈
- javascript函数调用不起作用
- 为什么这个函数调用会破坏程序并导致未定义的变量
- 如何通过函数调用设置图像的src
- 从全局函数调用Ember控制器上的方法
- 为什么Jquery$.ajax在函数调用中触发所有statusCode,即使调用成功
- JavaScript函数调用(arg1)(arg2)
- 打印链接时,将javascript函数调用到链接中
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 无法从JavaScript中的函数调用对象属性
- 对中的函数调用进行排序是回调的唯一方法
- 函数调用方法有什么用
- Javascript:JSHint:应为赋值或函数调用,但实际看到的却是表达式
- HTML5(Bootstrap)通过函数调用运行动画
- 函数调用不起作用
- 函数中的Javascript函数调用