【问题标题】:How to Chain Dynamic Series of Async Actions Using Redux Thunk?如何使用 Redux Thunk 链接动态系列的异步操作?
【发布时间】:2018-02-28 19:39:50
【问题描述】:

规范

根据官方文档 (https://github.com/gaearon/redux-thunk),我知道 redux thunk 允许按顺序调度一系列异步操作,如下所示:

function makeSandwichesForEverybody() {
  return function (dispatch, getState) {
    return dispatch(
      makeASandwichWithSecretSauce('My Grandma')
    ).then(() =>
      Promise.all([
        dispatch(makeASandwichWithSecretSauce('Me')),
        dispatch(makeASandwichWithSecretSauce('My wife'))
      ])
    ).then(() =>
      dispatch(makeASandwichWithSecretSauce('Our kids'))
    ).then(() =>
      dispatch(getState().myMoney > 42 ?
        withdrawMoney(42) :
        apologize('Me', 'The Sandwich Shop')
      )
    );
  }
}

我的情况

但是,如果我有一个动态的动作数组想要遍历并调用呢?

let arrOfActions = [];
arrOfActions.push(action1);
arrOfActions.push(action2);
arrOfActions.push(action3);

如何使用 Promise 逻辑迭代地链接这些异步操作?为了最好地解释我的想法,我希望做这样的事情:

function thunkActionCreator() {
  return function (dispatch, getState) {
    for (let key of arrOfActions) {
      dispatch(arrOfActions[key]()).then(
        // run next action in arrOfActions here
      )
    }
  }
}

这种函数调用的动态迭代是否可行?如果有,语法是什么?

为了验证您确实可以调用函数数组中的函数,这是我找到的资源:@​​987654322@

为什么是动态的动作数组?

可能有更好的方法来考虑这一点,但我尝试使用此实现的原因是因为我有一系列函数需要按特定顺序调用。该数组将存储在 Redux 的存储中,我不确定如何才能从头到尾依次调用一系列函数。任何其他想法都会有所帮助!

【问题讨论】:

    标签: reactjs asynchronous promise redux redux-thunk


    【解决方案1】:

    前期免责声明;我认为您需要这样做的事实证明了您的代码库中存在更深层次的问题。您真的不应该将需要以特定顺序发生并且您事先不知道的异步函数列表排队。这是许多危险信号。

    但是你能做到吗?当然!

    function enqueueDynamicArray(functionArray) {
        let p = Promise.resolve();
        for(index in functionArray) {
            p = p.then(functionArray[index]);
        }
        return p;
    }
    

    编辑:每个 cmets,如果您可以依赖同步的功能;

    function callDynamicArray(functionArray) {
        for(index in functionArray){
            functionArray[index]();
        };
    }
    

    【讨论】:

    • 感谢您在回答问题的同时提供建议!如果我正在排队需要以特定顺序发生的同步功能列表,您还会说还有更深层次的问题吗?我在队列中运行的函数不需要异步,只要我按顺序运行动态数量的函数即可。
    • 我仍然对需要它的情况持怀疑态度,但解决方案变得简单得多。我将更新答案以包括同步状态的非承诺版本。
    • 再次感谢您的快速/有用的回复。但是,当使用 Redux 调度时,您的非承诺版本如何工作?由于我的所有函数本质上都是 Redux 操作,它们以不同的方式更新状态,但必须是同步的,调度操作的 for 循环不会只是异步触发它们吗?也许我对 Redux 调度动作的理解是错误的。对此有任何帮助的想法将不胜感激!
    • 哇哦。根据redux-docs中dispatch的定义,The store's reducing function will be called with the current getState() result and the given action synchronously.随意更正,但这似乎意味着为了从动态数组中同步触发dispatch,我只需做一个dispatch(functionArray[index]());
    猜你喜欢
    • 2018-01-31
    • 1970-01-01
    • 2017-03-03
    • 2019-04-01
    • 2020-02-22
    • 2021-10-04
    • 2017-09-26
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多