循环执行提取请求 [英] Performing Fetch Request in a Loop

查看:37
本文介绍了循环执行提取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on an application that returns a list of ids from first fetch request. After getting the ids, I have to loop through the ids and get details of each item and then display it on the screen.

  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)
        })
      })

  })

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

My question is that is looping the best way to get the results?

更新:Promise.all给我一些问题:

UPDATE: Promise.all is giving me issues:

更新:使用异步和等待

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功能来获取异步操作列表.一切成功后,它们便会完成.

You can use Promise.all functionality to fetch a list of async actions. They will be completed when all are successful.

这是Promise all的示例代码,请让我知道它的工作原理:)

Here is example of your code with Promise all, let me know how it works :)

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)));
}

这篇关于循环执行提取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆