2017-02-24 130 views
0
const tileApiPromises = []; 
response.data.forEach((tile) => { 
    return getPartnerToken(tile.id).then((response) => { 
     tileApiPromises.push(getTileContent(tile, response)); 
    }); 
}); 
console.log(tileApiPromises) // should give me an array of promises 
Promise.all(tileApiPromises) // The goal is to execute this. 

我在日誌中獲得空數組。我如何獲得forEach之外的承諾數組。謝謝你的幫助!如何在forEach循環後填充數組

+0

當我試圖地圖,我得到了一個未定義的承諾值。 :/ – user3651940

回答

1

你的代碼的問題是推送是異步完成的 - 因此,數組中沒有任何東西!

你說你嘗試過地圖(在評論中) - 你是否嘗試過這樣?

const tileApiPromises = response.data.map((tile) => { 
    return getPartnerToken(tile.id).then((response) => { 
     return getTileContent(tile, response); 
    }); 
}); 

,或者性感

const tileApiPromises = response.data.map(tile => 
    getPartnerToken(tile.id).then(response => getTileContent(tile, response)) 
); 
+0

雖然你的代碼比我的更性感。 :d – user3651940

0

您可以使用Array.map函數而不是forEach。

forEach總是返回undefined。

map函數迭代所提供的數組,並返回map函數中提供的回調函數中返回的累積數組值。

這裏是關於地圖功能的很好的文檔。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

+0

我嘗試使用.map,但是當console.log(tileApiPromises),我得到的promiseValue未定義。你可以給我一個我如何使用地圖來做這個例子嗎? – user3651940

+0

@ user3651940 - 您應該向您展示您如何在地圖 –

+0

中作爲@Jaromanda X在他的回答中提及。您是否嘗試在回調中返回價值? – lavish