首页 > 解决方案 > 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));

标签: javascriptconditional-statementsfetch

解决方案


简单检查该值就足够了,您检查它之前是否已设置,如果没有,则为其分配一个新值。这是一个使用示例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));

推荐阅读