Javascript 如何在forEach循环后填充数组
我在日志中得到了空数组。如何在forEach之外获得承诺数组。谢谢你的帮助 您可以使用Array.map函数代替forEach forEach总是返回未定义的 而map函数迭代提供的数组,并返回在map函数提供的回调中返回的值的累积数组 这是关于map函数的很好的文档。Javascript 如何在forEach循环后填充数组,javascript,arrays,foreach,es6-promise,Javascript,Arrays,Foreach,Es6 Promise,我在日志中得到了空数组。如何在forEach之外获得承诺数组。谢谢你的帮助 您可以使用Array.map函数代替forEach forEach总是返回未定义的 而map函数迭代提供的数组,并返回在map函数提供的回调中返回的值的累积数组 这是关于map函数的很好的文档。 代码的问题在于推送是异步完成的-因此,阵列中还没有任何内容 你说你试过地图(在评论中)——你是这样试的吗 const tileApiPromises = []; response.data.forEach((tile) =&g
代码的问题在于推送是异步完成的-因此,阵列中还没有任何内容 你说你试过地图(在评论中)——你是这样试的吗
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.
或者更性感
const tileApiPromises = response.data.map((tile) => {
return getPartnerToken(tile.id).then((response) => {
return getTileContent(tile, response);
});
});
当我尝试使用map时,我得到了未定义的承诺值:/我尝试使用.map,但当console.log(tileApiPromises)时,我得到了未定义的promiseValue。你能给我举个例子,说明我如何使用map来完成这个任务吗?正如@Jaromanda X在他的回答中提到的那样。您是否尝试在中返回值。然后回调?
const tileApiPromises = response.data.map(tile =>
getPartnerToken(tile.id).then(response => getTileContent(tile, response))
);