如何使用Redux Thunk链接动态系列的异步操作?

时间:2017-09-19 21:51:25

标签: reactjs asynchronous promise redux redux-thunk

规范

根据官方文档(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
      )
    }
  }
}

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

为验证您确实可以调用函数数组中的函数,这是我找到的资源:How to store functions into an array and loop through each in javascript

为什么采用动态动作数组?

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

1 个答案:

答案 0 :(得分:1)

前期免责声明;我认为您需要这样做的事实证明您的代码库存在更深层次的问题。你真的不应该排队需要按特定顺序发生的异步功能列表,而且你不会在高级时知道。那是一些危险信号。

但你能做到吗?当然!

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

编辑:根据评论,如果你可以依赖同步的功能;

function callDynamicArray(functionArray) {
    for(index in functionArray){
        functionArray[index]();
    };
}
相关问题