Arturas Zuta
Arturas Zuta

Reputation: 15

How to extract data from a resolved promise javascript?

I'm trying to extract data from NewsAPI - the result from the API I'm getting is a resolved promise and I can't figure out how to access the object inside of it.

///////////////////SAMPLE CODE

let raps;

var url = 'https://newsapi.org/v2/top-headlines?' +
          'category=sports&' +
          'q=raptors&' +
          'apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxx';
var req = new Request(url);
fetch(req)
    .then(function(response) {
        raps = response.json();
        return raps;
    });


 function data () {
     if(raps == undefined) {
         console.log("Data is being parsed")
     } else {
         console.log(raps);
         clearInterval(loadData);
         generateData(raps);
     }
 }

 const loadData = setInterval(data, 1000);

 function generateData(raps) {
     let newData = raps.articles;
     console.log(newData);
 }

/////////////////END OF SAMPLE CODE

What I'm getting back is:


Promise {<resolved>: {…}}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
articles: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
status: "ok"
totalResults: 26

I'm trying to access the articles array.

Upvotes: 0

Views: 9938

Answers (2)

Mark Small
Mark Small

Reputation: 414

The following works to retrieve the articles once. What your after seems to be polling the server every second, but it can easily be adapted. I've used newer async/await method of treating asynchronous queries as if they are synchronous, makes it easier to read and understand I feel, but you can still use fetch/then/catch if you need to, again, shouldn't be too difficult to refactor.

To explain my code further.

  1. I run the whole thing as an asychronous function, that gets called immediately, note the code is wrapped in a (async () => { ...})(); block.
  2. await basically means wait until resolved. So you can see I wait for the fetch to resolve, then I wait for the response json to resolve (this is the bit really that is missing from your solution)
fetch('https://api.com/values/1')
    .then(response => response.json())
    .then(json => console.log(json));

///////////////////SAMPLE CODE
(async () => {
  const url = 'https://newsapi.org/v2/top-headlines?' +
            'category=sports&' +
            'q=raptors&' +
            'apiKey=xxxxxxxxxxxxxxxxxxxxxx';

  const response = await fetch(url);
  let articles = null;
  if (response.ok) {
    const raps = await response.json();
    articles = raps.articles;
  }

  if (articles) {
    articles.forEach(article => console.log(article));
  } else {
    console.log('No articles');
  }
})();
/////////////////END OF SAMPLE CODE

Upvotes: 1

Cavdy
Cavdy

Reputation: 618

This should work...

let raps;

var url = 'https://newsapi.org/v2/top-headlines?' +
      'category=sports&' +
      'q=raptors&' +
      'apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxx';
var req = new Request(url);
fetch(req)
 .then(response => response.json())
 .then((data) => {
   raps = data;
 });


function data () {
   if(raps == undefined) {
      console.log("Data is being parsed")
   } else {
      console.log(raps);
      clearInterval(loadData);
      generateData(raps);
   }
}

const loadData = setInterval(data, 1000);

function generateData(raps) {
  let newData = raps.articles;
  console.log(newData);
}

Upvotes: 2

Related Questions