![](/img/trans.png)
[英]How can I achieve a flattened array of promises from a forEach loop?
[英]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.
我在日志中得到的是空数组。 我如何才能在forEach之外获得带有承诺的数组。 谢谢你的帮助!
您的代码的问题在于,推送是异步完成的-因此,数组中还没有任何内容!
您说您尝试过地图(在评论中)-您是否尝试过这样?
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))
);
您可以使用Array.map函数代替forEach。
forEach始终返回未定义。
而map函数会在提供的数组上进行迭代,并返回map函数提供的回调中返回的值的累积数组。
这是有关地图功能的不错的文档。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.