gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:06:23 24 4
gpt4 key购买 nike

我在长数组上使用 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 的函数没有返回语句,因此 result 是一个 undefined 数组。因此,Promise.all 无需等待。

此外,无需手动插入数组。一旦我们添加了 return 语句,您将拥有一组 promise ,并且 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));

关于javascript - 在 Array push() 方法之后解决 Promise 或添加回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55309894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com