javascript - 当从打字稿中的另一个 thunk 调用时,如何等待执行 promise 的 redux thunk
问题描述
我有一个在单击按钮时执行的主要 thunk。在这个 thunk 中,我想调用另一个 thunk 并等待它完成,然后再继续前进。第二个 thunk 执行带有嵌套承诺的承诺。但是,我无法弄清楚如何等待第二个 thunk 完成其异步操作。
我尝试return
在我的 thunk 上使用关键字来使调用同步。我不能使用 async 关键字,因为我需要它在 IE 11 中工作。
我也试图让我的第二次重击返回一个承诺,然后做这样的事情,dispatch(secondThunk()).then(...)
但是它说我的重击实际上并没有返回一个承诺。
这是我的一些代码:
export function mainThunk(): ThunkAction<void, void, void, AnyAction> {
return (dispatch: Dispatch<any>) => {
...do some stuff
dispatch(secondThunk());
...do other stuff
};
}
export function secondThunk(): ThunkAction<void, void, void, AnyAction> {
return (dispatch: Dispatch<any>) => {
return new Promise((resolve: any, reject: any) => {
someAsyncFunction()
.then((response) => {
return Promise.all(someArray.map(someId => {
return someOtherAsyncFunction(someId):
}));
})
.then((responses) => {
response.foreach(response => {
dispatch(someReduxAction(response.someField));
});
})
.then(() => {
resolve();
});
});
};
}
当我运行我的代码时,mainThunk 不会在执行之前等待 secondThunk 完成。你能帮我弄清楚如何使这项工作?
解决方案
您快到了。在您的 mainThunk 函数中,您需要等待承诺解决或拒绝。我用 Javascript 而不是 Typescript 编写了我的演示。不过原理是一样的。代码沙箱在这里
import axios from "axios";
function mainThunk() {
secondThunk()
.then(data => {
console.log("success");
console.log(data);
})
.catch(e => {
console.log("something went wrong");
console.log(e);
});
}
function secondThunk() {
return new Promise((resolve, reject) => {
axios
.get("https://swapi.co/api/people/")
.then(people => {
someOtherAsyncFunction().then(planets => {
const response = {
planets: planets,
people: people
};
resolve(response);
});
})
.catch(e => {
reject(e);
});
});
}
function someOtherAsyncFunction() {
return axios.get("https://swapi.co/api/planets/").then(response => {
return response;
});
}
mainThunk();
推荐阅读
- c# - XML 转换为 Json 和 DeserializeObject 问题 - InfoPath 命名空间?
- javascript - 函数类型的可选参数
- python - 在 AppEngine Python 3.7 Standard 中安装 python3-saml 失败
- python - Python 单元素集到 JSON
- c# - 如果我的布尔值始终为真,我将如何检查单个灯
- javascript - 单击React js中的按钮时如何获取innerHTML?
- arrays - 在 Julia 中连接多维数组
- javascript - 如何修复 Not a number 值?
- cmake - 找不到路径中的 CMake 编译器
- javascript - 如何使用复选框隐藏函数内的元素?