JSFiddle - React, Tailwind, and code Playground

by baconpat

HTML

<pre id="output"/>

JavaScript

// Makes sequential getJSON requests, passing the processed results from the 
// previous request to the next request. seedData is optional.
var chainedGetJSON = function(requests, seedData) {
  var seed = $.Deferred(),
      finalPromise;

  finalPromise = requests.reduce(function(promise, request) {
    return promise.pipe(function(input) {
      return $.getJSON(request.url(input)).pipe(function(json) {
        return request.process(json, input);
      });
    });
  }, seed.promise());

  // Start the chain 
  seed.resolve(seedData);

  return finalPromise;
};

var thesaurusUrlForLastWord = function(words) {
  var word = words[words.length - 1];
  return "http://words.bighugelabs.com/api/2/2f0691be609ef56b97d1f8d5261c8bf3/" + word + "/json?callback=?";
};

// Make three sequential requests to the thesaurus API starting with the word "food". 
// Each subsequent request will do a new query using the last word returned from the previous result set
chainedGetJSON([
  { 
    url: thesaurusUrlForLastWord,
    process: function(json, words) {
      // Return synonyms
      return json.noun.syn;
    }
  },
  {
    url: thesaurusUrlForLastWord,
    process: function(json, words) {
      // Add new synonyms to the end
      return words.concat(json.noun.syn);
    }
  },
  {
    url: thesaurusUrlForLastWord,
    process: function(json, words) {
      // Add the first three synonyms to the beginning
      return json.noun.syn.slice(0,3).concat(words);
    }
  }
], ["food"]).then(function(words) {
  $('#output').text(words.join("\n"));
});