2017-10-20 2 views
0

Axios를 사용하는 함수를 사용하고 있습니다. 이 함수를 호출하고 반환하려는 배열을 가져올 수 있어야합니다. 불행히도 나는 undefined로 돌아가고있다. 나는 그것이 잘못 돌아 왔는지 또는 api 호출을하는 데 시간이 걸리는 액시오와 관련이 있는지를 모른다. 내가 지금처럼이 함수를 호출하고 로그 아웃하는 경우Axios 함수가 js로 값을 반환하지 않습니다.

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

:

console.log(filterItemsByRadius(userRadius, items)); 

가 그럼 난 정의되지 않은 얻을 것이다

여기 내 코드입니다. 나는 돌아 오는 데이터를 로그 아웃했고 올바른 정보를 가진 배열이므로 리턴하는 방식에 문제가있을 것입니다.

답변

2

이 함수는 약속을 반환합니다. 다음과 같이 부를 수 있습니다 :

filterItemsByRadius(userRadius, items).then(resp => { 
    console.log(resp); 
}); 

이제 콘솔에서 결과를 볼 수 있습니다.

관련 문제