首页 > 解决方案 > 当从打字稿中的另一个 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 完成。你能帮我弄清楚如何使这项工作?

标签: javascripttypescriptpromiseredux-thunk

解决方案


您快到了。在您的 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();


推荐阅读