[英]Node.JS API call returns UNDEFINED
I am trying to make my first API call with NodeJS by using node-fetch , however I am getting UNDEFINED as error.我正在尝试使用node-fetch使用 NodeJS 进行我的第一个 API 调用,但是我收到 UNDEFINED 作为错误。
The call works great on my browser link , however with the code below, it returns undefined:该调用在我的浏览器链接上效果很好,但是使用下面的代码,它返回未定义:
import fetch from 'node-fetch';
const latLongAirports = [{
"name": "Madrid",
"iata": "MAD",
"lat": 40.49565434242003,
"long": -3.574541319609411,
},{
"name": "Los Angeles",
"iata": "LAX",
"lat": 33.93771087455066,
"long": -118.4007447751959,
},{
"name": "Mexico City",
"iata": "MEX",
"lat": 19.437281814699613,
"long": -99.06588831304731,}
]
export function getTemperature(iata){
let data = latLongAirports.find(el => el.iata === iata);
var url = "http://www.7timer.info/bin/api.pl?lon=" + data.long + "&lat=" + data.lat + "&product=astro&output=json"
console.log(url);
async () =>{
const response = fetch(url);
const data2 = await response.json();
console.log(data2);
}
}
console.log(getTemperature('MEX'));
Any ideas why I am not getting the data?为什么我没有得到数据的任何想法?
getTemperature()
missing return
statement getTemperature()
缺少return
语句fetch()
not await
ed fetch()
不await
edasync ()=>{}
but never invoke itasync ()=>{}
但从未调用它Simply make getTemperature()
become async
and await
to it, also await
to fetch
and return
the result.只需让
getTemperature()
变为async
并await
它,也await
fetch
并return
结果。
export async function getTemperature(iata){
let data = latLongAirports.find(el => el.iata === iata);
var url = "http://www.7timer.info/bin/api.pl?lon=" + data.long + "&lat=" + data.lat + "&product=astro&output=json"
console.log(url);
const response = await fetch(url);
const data2 = await response.json();
console.log(data2);
return data2;
}
console.log(await getTemperature('MEX'));
I suggest making the whole getTemperature
function an async function
.我建议将整个
getTemperature
函数getTemperature
async function
。 Also use a try ... catch
block when await
something.在
await
某些东西时也使用try ... catch
块。
export async function getTemperature(iata) {
/* ... */
try {
const response = await fetch(url);
const data2 = await response.json();
return data2;
} catch (ex) {
throw ex;
}
}
Now your getTemperature
function will return a promise as well现在你的
getTemperature
函数也将返回一个 promise
// then/catch
getTemperature("MEX").then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.message);
});
// or async/await
( async function () {
try {
const result = await getTemperature("MEX");
console.log(result);
} catch (ex) {
console.log(ex.message);
}
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.