Reputation: 103
I am using Promise to log the response from an api. But everytime the body is logging in as null. Most probably due to async call
For calling api from fetch.
function getDetails(url){
return new Promise((resolve, reject) => {
fetch(url, {mode: 'no-cors'}).then(res => {
resolve(res);
}, error => {
console.log(err);
})
})
}
var u = "https://get.geojs.io/v1/ip/country.json";
getDetails(u).then(function(resp){
console.log(resp);
})
I expect the response of the api in console
Upvotes: 1
Views: 10078
Reputation: 21911
fetch()
already returns a Promise
so get rid of the new Promise(...)
part
function getDetails(url) {
return fetch(...).then(...);
}
fetch()
returns a Response
object and not something that has already been parsed for you. You have to call .json()
on it to get the response parsed by JSON.parse()
.
function getDetails(url) {
return fetch(url, {mode: 'no-cors'}).then(response => response.json());
}
This should already work, but with your setup will throw a syntax error:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
To get this fixed remove mode: 'no-cors'
Adding it all together will give us:
function getDetails(url) {
return fetch(url).then(response => response.json());
}
var u = "https://get.geojs.io/v1/ip/country.json";
getDetails(u).then(function(data) {
console.log(data);
})
Upvotes: 4