0

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

mgarcia
  • 5,669
  • 3
  • 16
  • 35
Ayush Koshta
  • 93
  • 1
  • 10
  • `fetch()` already returns a `Promise`, hence `new Promise(...)` is unnecessary – Andreas Jun 08 '19 at 08:00
  • If I just do fetch and .then() in the function without returning anything still the body is null – Ayush Koshta Jun 08 '19 at 08:03
  • `fetch()` returns a [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). – Andreas Jun 08 '19 at 08:03
  • function getDetails(url){ fetch(url, {mode: 'no-cors'}).then(res => { console.log(res) ; },error => { console.log(err); }) } – Ayush Koshta Jun 08 '19 at 08:05
  • Possible duplicate of [Trying to use fetch and pass in mode: no-cors](https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors). Don’t use 'no-cors' mode. – sideshowbarker Jun 08 '19 at 10:23

1 Answers1

3

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);
})
Andreas
  • 21,535
  • 7
  • 47
  • 56