在redux调度ActionCreator上绑定变量

时间:2016-11-29 18:01:30

标签: javascript reactjs redux redux-thunk

我有一系列的承诺,我试图将新的promises推送到另一个dispatch.then函数内的数组中,但似乎数组总是超出范围

load(params, auth) {
    return dispatch => {
        const { passage, versions, language_tag } = params
        let promises = []

        versions.forEach((id) => {
            // get the version info, and then pass it along
            dispatch(ActionCreators.version({ id: id })).bind(promises).then((version) => {
                promises.push(dispatch(ActionCreators.passages({
                    id: id,
                    references: [passage],
                    versionInfo: {
                        local_abbreviation: version.abbreviation,
                        local_title: version.title,
                        id: version.id,
                    },
                })))
            })
        })
        // 
        promises.push(dispatch(ActionCreators.configuration()))
        promises.push(dispatch(ActionCreators.byRef({ language_tag })))

        console.log(promises.length)
        return Promise.all(promises)
    }
},

我尝试了一些不同的方法,例如在版本循环内部调度之前设置var that = this,以及此处显示的内容,尝试在调度上使用.bind(promises)

promises.length总是2,(因为两个实际上被推到底部)。我可以在.then内部控制语句,所以我知道它已被执行,但调度不会在promises数组中结束。

我很可能会以错误的方式思考调度功能。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

问题在于,由于您在then()上添加了承诺,因此您在添加承诺时已经返回了数组。所以他们确实得到了补充,但为时已晚。

相反,试试这个:

load(params, auth) {
  return dispatch => {
    const { passage, versions, language_tag } = params;
    let promises = [];

    versions.forEach((id) => {
      // get the version info, and then pass it along
      promises.push(dispatch(ActionCreators.version({ id: id })).then((version) => {
        return dispatch(ActionCreators.passages({
          id: id,
          references: [passage],
          versionInfo: {
            local_abbreviation: version.abbreviation,
            local_title: version.title,
            id: version.id,
          },
        }));
      }));
    });
    //
    promises.push(dispatch(ActionCreators.configuration()));
    promises.push(dispatch(ActionCreators.byRef({ language_tag })));

    console.log(promises.length);
    return Promise.all(promises)
  }
}