简体   繁体   中英

Why is "Promise { <pending> }" not resolving?

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");

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)
});

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);

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)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM