对值进行简单的检查就足够了,您可以检查之前是否设置过它,如果没有,则为其分配一个新值
async/await
let geoInfo = {
ip: null,
user: null,
country: null
};
async function getGeoInfo() {
geoInfo.ip = geoInfo.ip || (await fetch('https://api.ipify.org?format=json').then(res => res.json())).ip;
geoInfo.user = geoInfo.user || (await fetch('https://www.iplocate.io/api/lookup/' + geoInfo.ip).then(res => res.json()));
geoInfo.country = geoInfo.country || (await fetch('https://restcountries.eu/rest/v2/alpha/' + geoInfo.user.country_code).then(res => res.json()));
return geoInfo;
}
getGeoInfo().then(res => console.log(res)).catch(err => console.log(err));