JSFiddle - React, Tailwind, and code Playground
JavaScript
var App = (function ($) {
// Gets the scenario from the API
// sugar for $.ajax with GET as method - 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) {
var instruction = [];
for (i=0; i<data.endpoints.length; i++) {
// We map it onto a new instruction object
instruction[i] = {
method: data.endpoints[i].method,
type: data.endpoints[i].type,
endpoint: data.endpoints[i].endPoint,
frequency: data.base.frequency
};
}
console.log('Instructions recieved:');
console.log(instruction);
// And now we create a promise from this
// instruction so we can chain it
var deferred = $.Deferred();
deferred.resolve(instruction);
return deferred.promise();
};
// This wraps the setTimeout into a promise, again
// so we can chain it
var waitForTimeout = function(instruction) {
//This is the issue with the code...for some reason despite having multiple promises setup--the chain only continues for the first promise in the array...despite the for loop
var deferred = [];
for (i=0; i < instruction.length; i++){
console.log('Waiting for ' + instruction[i].frequency + ' ms');
deferred[i] = $.Deferred();
setTimeout(function() {
deferred[i].resolve(instruction[i])
}, instruction[i].frequency);
return deferred[i].promise();
}
};
// Final step: call the API from the
// provided instructions
var callApi...