0

In my code, I want to load 2 JSON files first, then based on the result of the them, run another two JSON files, and then run a sequence of functions such as render, DOM etc. I want to save the JSON data in variable so I can refer to them later in the code.

Something like this:

$.when(parseJSON1(), parseJSON2())
  .then(
    parseJSON3(station_data.dj), parseJSON4(station_data.songurl)
  )
  .then(
    _cacheOptions
  )
  .then(
    _cacheDom
  )
  .then(`enter code here`
    _events

  ).then(
    _render
  );

  });

  var station_data, history_data, itunes_data, coverList_data;

  // Core Functions

  function _cacheOptions() {
    station_data = stationInfo[0];
    history_data = stationHistory[0];
    itunes_data = itunesInfo[0];
    coverList_data = coverInfo[0];
  }

  function _cacheDom() {}

  function _events() {}

  function _render() {}

  // Functions

  function parseJSON1() {
    return $.getJSON(settings.JSON1);
  }

  function parseJSON2() {
    return $.getJSON(settings.JSON2);
  }

  function parseJSON3(searchTerm) {
    return $.getJSON(settings.JSON3);
  }

  function parseJSON4() {
    return $.getJSON(settings.JSON4);
  }

So to make it simple, I want to run JSON1 and JSON2, then save its data as variables, then based on that data run JSON3 and JSON4 and save their variables. Then run the rest of the main functions.

The above would be the backbone of the plugin and I am trying to keep it very structural that everything runs on order.

Any idea how to make it work?

DannyBoy
  • 434
  • 5
  • 21

1 Answers1

1

Answer:

You can use $.when in combination with $.getJSON like you have been, however it would be best to wrap this into a async function so that you don't have to worry about so many moving parts.

  • Create a store object for returned json.
  • Get the first two datasets
  • Put data in store
  • Check on your first two returned datasets
  • if the check passes continue the promise chain
  • Get the last two datasets with a $.when call
  • Put data in store
  • Return store
  • do something afterwards by using getAll().then(fn)

async function getAll() {
  let json_store = {},
    combine = (...locations) => locations.map($.getJSON),
    json_check = (first, second) => (first.userId && second.userId);

  await $.when(...combine(settings.JSON1, settings.JSON2)).then(function([first], [second]) {
    json_store = Object.assign(json_store, {
      first,
      second
    });

    if (json_check(first, second)) {
      return $.when(...combine(settings.JSON3, settings.JSON4)).then(function([third], [fourth]) {
        json_store = Object.assign(json_store, {
          third,
          fourth
        });
      });
    }
  })
  return json_store;
};

getAll().then(console.dir);

Example:

let settings = {
  JSON1: "https://jsonplaceholder.typicode.com/todos/1",
  JSON2: "https://jsonplaceholder.typicode.com/todos/2",
  JSON3: "https://jsonplaceholder.typicode.com/todos/3",
  JSON4: "https://jsonplaceholder.typicode.com/todos/4"
}


async function getAll() {
  let json_store = {},
    combine = (...locations) => locations.map($.getJSON),
    json_check = (first, second) => (first.userId && second.userId);

  await $.when(...combine(settings.JSON1, settings.JSON2)).then(function([first], [second]) {
    json_store = Object.assign(json_store, {
      first,
      second
    });

    if (json_check(first, second)) {
      return $.when(...combine(settings.JSON3, settings.JSON4)).then(function([third], [fourth]) {
        json_store = Object.assign(json_store, {
          third,
          fourth
        });
      });
    }
  })
  return json_store;
};

getAll().then(console.dir);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
zfrisch
  • 8,474
  • 1
  • 22
  • 34
  • This solution surely works, but when I use it with the rest of the code it does not work since there is no place for other chaining functions such as `_cacheOptions`, `_cacheDom` etc.. – DannyBoy Aug 06 '19 at 20:35
  • @DannyBoy well - I'm confused? to continue the chain, instead of returning json_store, just return a promise. You'll be able to chain from there. Does that make sense? – zfrisch Aug 09 '19 at 02:44