简体   繁体   English

在forEach循环后如何填充数组

[英]How can I fill the array after forEach loop

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.

I am getting empty array of course in the log. 我在日志中得到的是空数组。 How can I get array with promises outside the forEach. 我如何才能在forEach之外获得带有承诺的数组。 Thanks for your help! 谢谢你的帮助!

The problem with your code is that the push is done asynchronously - therefore, there's nothing in the array yet! 您的代码的问题在于,推送是异步完成的-因此,数组中还没有任何内容!

you say you tried map (in the comment) - did you try it like this? 您说您尝试过地图(在评论中)-您是否尝试过这样?

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

or, sexier 或者,更性感

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

You can use Array.map function instead of forEach. 您可以使用Array.map函数代替forEach。

forEach always return undefined. forEach始终返回未定义。

while map function iterates over array provided and returns accumulated array of values returned in callback provided in map function. 而map函数会在提供的数组上进行迭代,并返回map函数提供的回调中返回的值的累积数组。

Here is nice documentation on map function. 这是有关地图功能的不错的文档。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM