JSFiddle - React, Tailwind, and code Playground
JavaScript
var App = (function ($) {
// Gets the scenario from the API
// NOTE: this returns a promise
var getScenario = function () {
console.log("Getting scenario ...");
return $.get("http://demo3858327.mockable.io/scenario2");
};
// The result of the previous promise is passed into the
// next as we're chaining. So the data will contain the
// result of getScenario
var mapToInstruction = function (data) {
// We map it onto a new instruction object
var res = $.map(data.endpoints, function(val, key) {
return {
method:val.method,
type:val.type,
endpoint:val.endPoint,
frequency:data.base.frequency
}
});
console.log("Instructions recieved:", res);
return res
};
// This wraps the setTimeout into a promise, again
// so we can chain it
var waitForTimeout = function(instruction) {
var res = $.when.apply(instruction,
$.map(instruction, function(val, key) {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.notify("Waiting for " + val.frequency + " ms")
dfd.resolve(val);
}, Number(val.frequency) * (1 + key));
return dfd.promise()
})
})
)
.then(function() {
return this
}, function(err) {
console.log("error", err)
}
, function(msg) {
console.log("\r\n" + msg + "\r\nat " + $.now() +"\r\n")
});
return res
};
// Final step: call the API from the
// provided instructions
var callApi = function(instruction) {
console.log("Calling API with given instructions ...", instruction);
var res =...