2016-11-29 32 views
0

我有一個承諾數組,我試圖將新的承諾推入另一個dispatch.then函數內的數組中,但它看起來該數組總是超出範圍在redux dispatch上的綁定變量ActionCreator

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內部控制語句,所以我知道它正在執行,但調度並沒有在promise數組中結束。

我很可能以錯誤的方式思考調度功能。

任何幫助,將不勝感激!

回答

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) 
    } 
} 
+0

嘿!感謝你的回答。現在所有的調度都在推送,除了它說的是在通道調度中的'version'是未定義的。我也嘗試'.bind(version)'。 – jacoballenwood

+0

不要綁定任何東西,因爲它不起作用。上面的代碼明確假定版本是第一個動作創建者的許諾所解決的。這可能並非如此。因此,請查看「ActionCreators.version」中的問題。確保它返回一個'Promise',並確保承諾解析爲期望的版本對象。 – DDS

+0

其實我錯了,說版本是未定義的,它是在視圖文件中的其他東西!這很好,謝謝! – jacoballenwood