【问题标题】:How do I fetch several variablesHow do I fetch several variables
【发布时间】:2022-12-26 15:48:52
【问题描述】:

I want to display the news with categories using API. So I'm trying to use await fetch with several variables but it doesn't work. any idea to fix?

const API_KEY = "api key";
const HEADLINES_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&apiKey=";
const GENERAL_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&category=general&apiKey=";
const BUSINESS_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=";
const SPORTS_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&category=sports&apiKey=";
const ENTERTAINMENT_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&category=entertainment&apiKey=";
const TECHNOLOGY_NEWS =
  "https://newsapi.org/v2/top-headlines?country=us&category=technology&pageSize=8&apiKey=";
const SEARCH_NEWS = "https://newsapi.org/v2/everything?q=";

This part makes error.

  const response = await fetch([  
    GENERAL_NEWS + API_KEY,
    BUSINESS_NEWS + API_KEY,
    SPORTS_NEWS + API_KEY,
    TECHNOLOGY_NEWS + API_KEY,
    ENTERTAINMENT_NEWS + API_KEY,
  ]);

newsDataArr = [];
  if (response.status >= 200 && response.status < 300) {
    const myJson = await response.json();
    newsDataArr = myJson.articles;
  } else {
    // handle errors
    console.log(response.status, response.statusText);
    newsdetails.innerHTML = "<h5>No data found.</h5>";
    return;
  }

  displayNews();
};

【问题讨论】:

    标签: javascript


    【解决方案1】:

    You can not specify multiple endpoints for fetch() directly. Instead, you can wrap all calls separately with Promise.allSettled and send them in the same time:

    const results = await Promise.allSettled([
      fetch(GENERAL_NEWS + API_KEY),
      fetch(BUSINESS_NEWS + API_KEY),
      fetch(SPORTS_NEWS  + API_KEY),
      fetch(TECHNOLOGY_NEWS + API_KEY),
      fetch(ENTERTAINMENT_NEWS + API_KEY),
    ]);
    

    【讨论】:

      猜你喜欢
      • 2022-12-28
      • 2022-01-04
      • 2022-12-01
      • 2013-04-23
      • 2022-12-27
      • 2022-12-19
      • 2022-11-20
      • 2022-12-02
      • 2022-12-01
      相关资源
      最近更新 更多