title: Conditional fetch chaining in javascript
body: <p>I want to fill an object <code>geoInfo</code> getting data from 3 endpoints using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" rel="nofollow noreferrer"><code>fetch</code></a>, initial object is like:</p>
  <pre class="lang-js prettyprint-override"><code>let geoInfo = {
      ip: null,
      user: null,
      country: null
  };
  </code></pre>
  <p>I will call this function many times, thats why I want to add conditions: if <code>geoInfo.ip</code> is set, it musn´t run the first fetch and if <code>geoInfo.user</code> is set, it musn´t run the second <code>fetch</code> too. How Can I handle this?</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>let geoInfo = {
    ip: null,
    user: null,
    country: null
  };
  
  // Get user info based on ip.
  function getGeoInfo() {
    return new Promise((resolve, reject) =&gt; {
  
      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 =&gt; console.log(res)).catch(err =&gt; console.log(err));</code></pre>
  </div>
  </div>
  </p>