Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

javascript - Result is not pushing to blank array

I am trying to get five (5) articles from a news API and to push those results into a blank array titled "topNews"

I believe the issue lies in the getNews function listed below not writing to the blank array created at the top of the file.

The fetch is working and I can see the array coming back with .then((result) => console.log(result))

I am trying to push it into the new array that I call in the next function to display the results but when I console.log the topNews array with, I get undefined.

Any help would be appreciated.

let twitterTrends = [];
let topNews = [];
let numOfCompleted = 0;

function getTrends() {
  var myHeaders = new Headers();
  myHeaders.append(
    "Authorization",
    "Bearer ********");
  myHeaders.append(
    "Cookie",
    'personalization_id="v1_QSZs3kHuqI6knlNtIbIchQ=="; guest_id=v1%3A159630901122767291'
  );

  var requestOptions = {
    method: "GET",
    headers: myHeaders,
    redirect: "follow",
  };

  const url =
    "https://cors-anywhere-gp.herokuapp.com/https://api.twitter.com/1.1/trends/place.json?id=23424977";

  fetch(url, requestOptions)
    .then((response) => response.json())
    .then((responseJson) => topFive(responseJson))
    .catch((error) => console.log("error", error));
}

function topFive(responseJson) {
  $("#results").html("<h2>Loading Twitter Trends...</h2>");
  for (let i = 0; i < 5; i++) {
    $("#results").append(`<p>${responseJson[0].trends[i].name}</p>`);
    twitterTrends.push(responseJson[0].trends[i].name);
    setTimeout(
      () => getNews(responseJson[0].trends[i].name.replace("#", ""), i),
      2000
    );
  }
  showTrends();
}

function getNews(topic, index) {
  var requestOptions = {
     method: "GET",
  };

  var params = {
    api_token: "*******",
    search: { topic },
    limit: "5",
  };

  fetch(
    `https://api.thenewsapi.com/v1/news/all?api_token=*******&search=${topic}&limit=5`,
    requestOptions
  )
    .then((response) => response.json())
    .then((result) => {
      topNews[index] = result.value;
      checkNewsDone();
    })
    .catch((error) => console.log("error", error));
}

function checkNewsDone() {
  numOfCompleted++;
  $("#results").append(`<p>Loading ${numOfCompleted} of 5</p>`);
  if (numOfCompleted === 5) {
    renderData();
  }
}

function renderData() {
  console.log(topNews[0]);
  let html = "";
  for (let i = 0; i < twitterTrends.length; i++) {
    html += "<section class='news'>";
    html += `<h2>${twitterTrends[i]}</h2>`;
    html += "<ul class='articles'>";
    for (let j = 0; j < topNews[i].length; j++) {
      html += `<li>
        ${
          topNews[i][j].image && topNews[i][j].image.thumbnail
            ? `<div class="thumbnail" style="background-image:url('${topNews[i][j].image.thumbnail.contentUrl}')"></div>`
            : ""
        }
        <h3><a href="${topNews[i][j].url}" target="_blank">${
        topNews[i][j].name
      }</a></h3>
        <p>${topNews[i][j].description}</p>
      </li>`;
    }
    html += "</ul></section>";
  }
  html +=
    "<button type='button' class='js-restart button'>Refresh Results</button>";
  $("#results").html(html);
}

function showTrends() {
  let html = "";
  html += "<section class='twitter'>";
  html += "<ul class='trends'>";
  for (let i = 0; i < 5; i++) {
    html += `<li>${twitterTrends[i]}</li>`;
  }
  html += "</ul></section>";
  $(".topFiveTrends").html(html);
}

function getAgain() {
  $("#results").on("click", ".js-restart", function () {
    $("#results").html("");
    twitterTrends = [];
    topNews = [];
    numOfCompleted = 0;
    getTrends();
  });
}

function watchStart() {
  getTrends();
  $(".js-startButton").on("click", function (event) {
    $(".startPage").addClass("hidden");
    $(".topFiveTrends").addClass("hidden");
    $(".startButton").addClass("hidden");
    $("#results").removeClass("hidden");
  });
}

$(watchStart);
$(getAgain);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't show us the code where you log the array, which is where the issue lies. You also don't show us how topNews is defined.

You're console logging long before the .then() finishes. To get the value, you have to chain another .then() to wait for it.

If you're console logging outside the function, return the entire promise with return fetch(...).then..., and get the value with:

getNews(...).then(() => { /* now you have access to the full topNews array */ });


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...