在 Array push() 方法之后解决 Promise 或添加回调

Resolve Promise or add Callback after Array push() method

我在长数组上使用 map() 并对每个值使用 fetch。这将需要很多秒才能完成。我想知道最后的推送是什么时候完成的,并使用数组中的数据。

我尝试了 Promise、Promise.all、Async/Await,但可能遗漏了一些明显的东西。我创建此示例代码是为了更简单地说明问题。

const arr = new Array(100).fill("todos")
const arrPush = []

const result = arr.map(data => {
  fetch(`https://jsonplaceholder.typicode.com/${data}`)
  .then(res => res.json())
  .then(res => arrPush.push(res))
})

Promise.all(result).then(() => console.log(arrPush))

当最终值添加到数组时,做一些事情。在这种情况下 console.log 完整的数组。

您传递给 map 的函数没有 return 语句,因此 result 是一个 undefined 数组。因此,Promise.all 没有什么可等待的。

此外,无需手动推入数组。一旦我们添加了 return 语句,您将拥有一组承诺,并且 Promise.all 将解析为一个包含您当前尝试推送的所有内容的数组。

所以试试这个:

const arr = new Array(100).fill("todos")
const promises = arr.map(data => {
  return fetch(`https://jsonplaceholder.typicode.com/${data}`)
    .then(res => res.json());
});

Promise.all(promises)
  .then(arrayOfResults => console.log(arrayOfResults));