Gerry de Caires
Gerry de Caires

Reputation: 1

Store Response Results in Variables

I'm trying to learn how to use the newsapi.org api function to pull headlines and put them on my site. I have their function which I've tested in the Chrome console and it works fine but what I can't figure out is how to access the results from within the array. Here is the function:

function pullNews() {    
var url = 'https://newsapi.org/v2/top-headlines?' +
          'country=ca&' +
          'apiKey=b96fda738da54749986d258f6d5f9682';
var req = new Request(url);
fetch(req)
    .then(function(response) {
        console.log(response.json());
    })    
}

I would prefer to learn this on my own so if anyone can point me in the right direction, maybe even the correct phrase to search I would appreciate it greatly.

Upvotes: 0

Views: 255

Answers (2)

Negi Rox
Negi Rox

Reputation: 3932

<!DOCTYPE html>
<html>
<body>

<h2>Pure javascript</h2>

<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>

<script>
function loadXMLDoc() {
var url = 'https://newsapi.org/v2/top-headlines?' +
      'country=ca&' +
      'apiKey=b96fda738da54749986d258f6d5f9682'
 var xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function() {
 if (this.readyState == 4 && this.status == 200) {

  console.log(JSON.parse(this.responseText));
  }
 };
xhttp.open("GET",url , true);
xhttp.send();
}
</script>
</body>
</html>

--------------------JQuery---------------

var url = 'https://newsapi.org/v2/top-headlines?' +
      'country=ca&' +
      'apiKey=b96fda738da54749986d258f6d5f9682'
$.getJSON(url,function(data){console.log(data)})

--------------Request Object--------------

var req = new Request(url);
fetch(req).then(function(response) {return response.json();})
    .then(function(json) {
        console.log(json);
    });

Upvotes: 0

Daniel Conde Marin
Daniel Conde Marin

Reputation: 7742

The method json on the response returned by fetch returns a Promise, which you are console logging. To see the actual results you would need to wait until that promise is resolved as well:

function pullNews() {
    var url = 'https://newsapi.org/v2/top-headlines?' +
            'country=ca&' +
            'apiKey=b96fda738da54749986d258f6d5f9682';

    var req = new Request(url);

    fetch(req)
        .then(function(response) {
            return response.json(); // this is another promise that needs resolving
        })
        .then(function(json) {
            console.log(json);
        })
}

A bit tidier using async / await:

async function pullNews() {
    const url = 'https://newsapi.org/v2/top-headlines?' +
                'country=ca&' +
                'apiKey=b96fda738da54749986d258f6d5f9682';

    var req = new Request(url);
    const response = await fetch(req);
    return response.json();
}

(async function() {
    const result = await pullNews();
    console.log(result);
})();

Upvotes: 2

Related Questions