如何使用Redux Thunk链接一系列异步动作



norm

根据官方文档(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 Logic迭代地链接这些异步动作?为了最好地解释我在想什么,我希望做这样的事情:

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

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

为了验证您确实可以在功能数组中调用函数,这是我发现的资源:如何将函数存储到数组中并通过JavaScript中的每个函数

中的每个函数

为什么动态动作?

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

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

但是你能做到吗?当然!

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

最新更新