[英]Axios function not returning any values with js
I am using a function which uses axios. 我正在使用使用axios的功能。 I want to be able to call this function and get the array I am trying to return back.
我希望能够调用此函数并获取要返回的数组。 Unfortunately I am getting back undefined.
不幸的是,我回来了不确定。 I don't know if I am just returning it wrong or if it has to do with axios taking time to make an api call.
我不知道我是否只是将其返回错误,还是与axios花费时间进行api调用有关。
Here is my code: 这是我的代码:
const filterItemsByRadius = (userRadius, items) => {
axios
.get('http://ip-api.com/json')
.then(response => {
const data = [];
const { lat, lon } = response.data;
items.map(item => {
let itemGeolocation;
if (item.geolocation) {
itemGeolocation = item.geolocation.coords;
}
const currentLocation = {
latitude: lat,
longitude: lon,
};
const distanceArr = geolib.orderByDistance(currentLocation, [itemGeolocation]);
const miles = (distanceArr[0].distance / 1609.34).toFixed(2);
if (miles <= userRadius) {
data.push(item);
return data;
}
});
})
.catch(err => {
console.log(err);
});
};
If I call this function like so and log it out: 如果我这样调用此函数并注销:
console.log(filterItemsByRadius(userRadius, items));
Then I will get undefined. 然后我将变得不确定。 I have logged out the data that I am returning and it is an array with the correct information so I must be doing something wrong with how I am returning it.
我已经注销了要返回的数据,它是一个包含正确信息的数组,所以我在返回数据时一定做错了。
The function returns a promise. 该函数返回一个promise。 You can call it like this:
您可以这样称呼它:
filterItemsByRadius(userRadius, items).then(resp => {
console.log(resp);
});
You'll be able to see the result in the console now. 您现在可以在控制台中查看结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.