3

I am trying to fetch data from the Storm Glass API. I am using their template Fetch request (https://docs.stormglass.io/?javascript#point-request).

When I run the script the console reads out "Promise { <pending> }" indefinitely. So, the request is not returning a value but I can't work out why. Any ideas?

I have replaced my API key with <My API key>

const http = require('http')
const fetch = require('isomorphic-fetch');

http.createServer((req, res) => {

////////////////////////////////////////////////App code
const lat = 58.7984;
const lng = 17.8081;
const params = 'waveHeight,airTemperature';

fetch(`https://api.stormglass.io/point?lat=${lat}&lng=${lng}&params=${params}`, {
  headers: {
    'Authorization': '<My API key>'
  }
}).then(function(response) {
  // Do something with response data.
  const jsonData = response.json();
  console.log(jsonData)
});

/////////////////////////////////////////////////////////
}).listen(3000);

console.log("service running on http://localhost:3000");
Booncat
  • 33
  • 4

3 Answers3

5

The response.json function return a Promise, not the deserialized object. Your code should read:

fetch(`https://api.stormglass.io/point?lat=${lat}&lng=${lng}&params=${params}`, {
  headers: {
    'Authorization': '<My API key>'
  }
})
.then(response => response.json())
.then(function(jsonData) {
  // Do something with response data
  console.log(jsonData)
});
gretro
  • 1,934
  • 15
  • 25
1

As an aside to gretro's answer, you may have got the idea that const json = response.json() would work from looking at async/await code as it's very similar, so here's how that code might look if written that way. It's traditionally wrapped in a try/catch, so I've included that too.

http.createServer(async (req, res) => {

  const lat = 58.7984;
  const lng = 17.8081;
  const params = 'waveHeight,airTemperature';

  try {
    const endpoint = `https://api.stormglass.io/point?lat=${lat}&lng=${lng}&params=${params}`;
    const params = { headers: { 'Authorization': '<My API key>' } };
    const response = await fetch(endpoint, params);
    const jsonData = await response.json();
    console.log(jsonData);
  } catch (err) {
    console.error(err);
  }

}).listen(3000);
Andy
  • 61,948
  • 13
  • 68
  • 95
0

You can resolve promise by using async/awiat.

fetch(`https://api.stormglass.io/point?lat=${lat}&lng=${lng}&params=${params}`, {
  headers: {
    'Authorization': '<My API key>'
  }
})
.then(async response => {
    const jsonData = await response.json();
    console.log(jsonData)
})