【问题标题】:Why is "Promise { <pending> }" not resolving?为什么“Promise { <pending> }”没有解决?
【发布时间】:2019-04-07 15:22:54
【问题描述】:

我正在尝试从 Storm Glass API 获取数据。我正在使用他们的模板获取请求 (https://docs.stormglass.io/?javascript#point-request)。

当我运行脚本时,控制台会无限期地读出“Promise { &lt;pending&gt; }”。所以,请求没有返回值,但我不知道为什么。有什么想法吗?

我已将我的 API 密钥替换为 &lt;My API key&gt;

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

【问题讨论】:

    标签: javascript node.js isomorphic-fetch-api


    【解决方案1】:

    response.json 函数返回一个 Promise,而不是反序列化的对象。您的代码应为:

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

    【讨论】:

    • 如果想捕获非 200 状态,还应该检查 response.okresponse.status
    【解决方案2】:

    除了 gretro 的回答之外,您可能已经想到 const json = response.json() 可以通过查看 async/await 代码来工作,因为它非常相似,所以如果以这种方式编写代码可能看起来如何。传统上它被包裹在 try/catch 中,所以我也包含了它。

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

    【讨论】:

      【解决方案3】:

      您可以使用 async/awiat 解决 Promise。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-25
        • 1970-01-01
        • 1970-01-01
        • 2023-01-12
        • 1970-01-01
        • 2019-03-25
        • 2018-07-20
        相关资源
        最近更新 更多