代码之家  ›  专栏  ›  技术社区  ›  Hans Felix Ramos

javascript中的条件获取链

  •  0
  • Hans Felix Ramos  · 技术社区  · 4 年前

    我想填充一个对象 geoInfo 使用从3个端点获取数据 fetch ,初始对象如下:

    let geoInfo = {
        ip: null,
        user: null,
        country: null
    };
    

    我将多次调用此函数,这就是我想添加条件的原因:如果 geoInfo.ip 如果已设置,则不能运行第一次获取,如果 geoInfo.user 如果设置好了,就不能运行第二个 取来 我也是。我该怎么办?

    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));
    0 回复  |  直到 4 年前
        1
  •  2
  •   Krzysztof Krzeszewski    4 年前

    对值进行简单的检查就足够了,您可以检查之前是否设置过它,如果没有,则为其分配一个新值 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));
    
        2
  •  1
  •   Daniel_Knights    4 年前

    您可以在内部链接后续的获取请求 .then 并根据之前的数据是否已设置来添加条件:

    .then(function(data) { 
        geoInfo.ip = data.ip; 
        return fetch('https://www.iplocate.io/api/lookup/' + geoInfo.ip)
            .then(function(data) { 
                if (geoInfo.ip) return;
                return fetch('...and so on')
            }); 
    })