gpt4 book ai didi

javascript - 循环执行获取请求

转载 作者:行者123 更新时间:2023-12-01 01:10:39 25 4
gpt4 key购买 nike

我正在开发一个从第一个获取请求返回 ID 列表的应用程序。获取 ids 后,我必须循环遍历 ids 并获取每个项目的详细信息,然后将其显示在屏幕上。

  fetch(TOP_STORIES)
.then(function(response){
return response.json()
}).then(function(storyIds){
// storyIds is [22,33,44,55,66,77,88,99,123,213,342,45456,778,888]
// is this the best way to fetch all the details of the story
storyIds.forEach(function(storyId){

let storyDetailsURL = `https://someurl/v0/item/${storyId}.json?print=pretty`

fetch(storyDetailsURL)
.then((response) => response.json())
.then((story) => {
displayStory(story)
})
})

})

我的问题是循环是获得结果的最佳方法吗?

更新:Promise.all 给我带来了问题:

enter image description here

更新:使用异步和等待

async function fetchTopHeadlinesAsyncAwait() {

let response = await fetch(TOP_STORIES)
let storyIds = await response.json()

for(let storyId of storyIds) {
console.log(storyId)
let storyDetailsURL = `someurl/er/tg/${storyId}.json?print=pretty`
let response = await fetch(storyDetailsURL)
let story = await response.json()
displayStory(story)
}
}

最佳答案

您可以使用 Promise.all 功能来获取异步操作列表。当一切都成功时,它们就会完成。

这是使用 Promise all 的代码示例,请让我知道它是如何工作的:)

const fetchStories = () => {
let response = await fetch(TOP_STORIES);
let storyIds = await response.json();

let urls = [];
storyIds.forEach(function(storyId) {
urls.push(`https://someurl/v0/item/${storyId}.json?print=pretty`);
});

Promise.all(
urls.map(url =>
fetch(url)
.then(response => response.json())
.catch(err => console.error(err))
)
).then(stories => stories.forEach(story => displayStory(story)));
}

关于javascript - 循环执行获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169313/

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