javascript - javascript中的条件获取链接
问题描述
我想填充一个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));
解决方案
简单检查该值就足够了,您检查它之前是否已设置,如果没有,则为其分配一个新值。这是一个使用示例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));
推荐阅读
- mysql - Hibernate for Deployed MYSQL 的通信链路故障
- java - Apache POI 库中的 JNI 错误
- python - 如果 findall 找到搜索模式,则在文件中插入新行
- git - 有没有办法阻止我的本地存储库下载提交历史记录?
- java - 如何使用 ASM 存储动态生成的 java 类的类定义?
- javascript - 使用 php java-script 和 html 创建跟踪器
- azure - 有哪些可能用于 Web 应用程序 (AWS) 的无服务器系统架构以降低成本
- 8thwall-xr - 如何将物体放在检测到的表面上?
- python - django model_to_dict 包括指向模型的外键
- testing - 使用 Hamcrest 测试一个数组是否包含另一个数组中的元素