Я хочу заполнить объект geoInfo
, получая данные с 3 конечных точек, используя fetch
, начальный объект выглядит так:
let geoInfo = {
ip: null,
user: null,
country: null
};
Я буду вызывать эту функцию много раз, вот почему я хочу добавить условия: если установлен geoInfo.ip
, он не должен запускать первую выборку, а если geoInfo.user
установлен, он не должен запускать и вторую fetch
. Как мне с этим справиться?
let geoInfo = {
ip: null,
user: null,
country: null
};
// Get user info based on ip.
function getGeoInfo() {
return new Promise((resolve, reject) => {
let result = fetch('https://api.ipify.org?format=json')
.then(function(response) {
return response.json();
})
.then(function(data) {
geoInfo.ip = data.ip;
return fetch('https://www.iplocate.io/api/lookup/' + geoInfo.ip);
})
.then(function(response) {
return response.json();
})
.then(function(data) {
geoInfo.user = data;
return fetch('https://restcountries.eu/rest/v2/alpha/' + geoInfo.user.country_code);
})
.then(function(response) {
return response.json();
})
.then(function(data) {
geoInfo.country = data;
})
.catch(function(error) {
console.log('Request failed', error);
reject(error);
})
result.then(function(response) {
resolve(geoInfo);
});
});
}
getGeoInfo().then(res => console.log(res)).catch(err => console.log(err));