I am currently trying to fetch JSON from a website using the node-fetch module, and have made the following function:
var fetch = require("node-fetch");
function getJSON(URL) {
return fetch(URL)
.then(function(res) {
return res.json();
}).then(function(json) {
//console.log(json) logs desired data
return json;
});
}
console.log(getJson("http://api.somewebsite/some/destination")) //logs Promise { <pending> }
When this is printed to the console, I simply receive Promise { <pending> }
However, if I print the variable json
to the command line from the last .then function, I get the desired JSON data. Is there any way to return that same data?
(I apologize in advance if this is just a misunderstanding issue on my part, as I am rather new to Javascript)
A JavaScript Promise is asynchronous. Your function is not.
When you print the return value of the function it will immediately return the Promise (which is still pending).
Example:
var fetch = require("node-fetch");
// Demonstational purpose, the function here is redundant
function getJSON(URL) {
return fetch(URL);
}
getJson("http://api.somewebsite/some/destination")
.then(function(res) {
return res.json();
}).then(function(json) {
console.log('Success: ', json);
})
.catch(function(error) {
console.log('Error: ', error);
});