[英]Why is "Promise { <pending> }" not resolving?
I am trying to fetch data from the Storm Glass API.我正在尝试从 Storm Glass API 获取数据。 I am using their template Fetch request ( https://docs.stormglass.io/?javascript#point-request ).
我正在使用他们的模板 Fetch 请求 ( https://docs.stormglass.io/?javascript#point-request )。
When I run the script the console reads out " Promise { <pending> }
" indefinitely.当我运行脚本时,控制台会无限期地读出“
Promise { <pending> }
”。 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>
我已经用
<My API key>
替换了我的 API 密钥
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}¶ms=${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. response.json
函数返回一个 Promise,而不是反序列化的对象。 Your code should read:你的代码应该是:
fetch(`https://api.stormglass.io/point?lat=${lat}&lng=${lng}¶ms=${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.作为 gretro 答案的旁白,您可能已经想到
const json = response.json()
可以通过查看async/await
代码来工作,因为它非常相似,因此如果以这种方式编写,代码的外观如下所示。 It's traditionally wrapped in a try/catch
, so I've included that too.它传统上包含在
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}¶ms=${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.您可以使用 async/awiat 解决 promise。
fetch(`https://api.stormglass.io/point?lat=${lat}&lng=${lng}¶ms=${params}`, {
headers: {
'Authorization': '<My API key>'
}
})
.then(async response => {
const jsonData = await response.json();
console.log(jsonData)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.