【问题标题】:How to wait for a redux thunk that executes a promise when called from another thunk in typescript当从打字稿中的另一个 thunk 调用时,如何等待执行 promise 的 redux thunk
【发布时间】:2019-09-22 10:20:08
【问题描述】:

我有一个在单击按钮时执行的主 thunk。在这个 thunk 中,我想调用另一个 thunk 并等待它完成,然后再继续前进。第二个 thunk 执行带有嵌套承诺的承诺。但是,我无法弄清楚如何等待第二个 thunk 完成其异步操作。

我尝试在我的 thunk 上使用 return 关键字来使调用同步。我不能使用 async 关键字,因为我需要它在 IE 11 中工作。

我还尝试让我的第二个 thunk 返回一个承诺,然后执行类似 dispatch(secondThunk()).then(...) 的操作,但它说我的 thunk 实际上并没有返回一个承诺。

这是我的一些代码:

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 完成。你能帮我弄清楚如何完成这项工作吗?

【问题讨论】:

    标签: javascript typescript promise redux-thunk


    【解决方案1】:

    你快到了。在您的 mainThunk 函数中,您需要等待承诺解决或拒绝。我用 Javascript 而不是 Typescript 编写了我的演示。不过原理是一样的。 Code-sandbox here

    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();
    
    

    【讨论】:

    • 但是,这是使用 thunk 动作创建者,这与您所拥有的不同。如您所见,我必须使用 dispatch 调用 secondThunk,并且我也在使用 TypeScript。当我尝试在 secondThunk 上执行 then 时,我收到错误 property then does not exist in on type ThunkAction
    猜你喜欢
    • 2018-09-29
    • 2017-09-10
    • 2021-04-20
    • 2017-12-17
    • 2023-03-23
    • 2021-09-25
    • 2017-06-15
    • 1970-01-01
    • 2019-03-02
    相关资源
    最近更新 更多