In the JavaScript demo below, the RSVP.js Promise Library is utilized to load JSON data using AJAX. Once the JSON data is loaded, additional Promises are desired that do not involve AJAX requests.
One of the requirements after loading the JSON data is to create a new Promise that will execute a function responsible for setting up DOM Event handlers/listeners.
Following the setup of Event handling, another function needs to be executed after all events have been set up.
Due to being new to Promises and still learning JavaScript, assistance in adding more Promises to the code would be greatly appreciated. An example code expansion with guidance on JSFiddle would be very helpful!
To view the JSFiddle Demo of the code, click here: http://jsfiddle.net/jasondavis/fttzoggj/
var jsonPromiseCache = {};
// Function to load JSON data via AJAX using Promise()
var getJsonDataPromise = function(url, key) {
if (!jsonPromiseCache[key]) {
jsonPromiseCache[key] = new RSVP.Promise(function(resolve, reject){
var client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
jsonPromiseCache[key] = this.response;
resolve(this.response);
} else {
reject(this);
}
}
};
});
}
return jsonPromiseCache[key];
};
// EXAMPLE USAGE DEMO
var promises = {
users: getJsonDataPromise('/echo/json/', 'users'),
task: getJsonDataPromise('/echo/json/', 'task')
};
RSVP.hash(promises)
.then(function(results) {
// Additional operations after successful loading of JSON data
})
.finally(function(){
console.log('finally() function ran on success and failure.... It is always ran!');
})
.catch(function(reason){
console.log('[ERROR] REASON:',reason.statusText);
});
UPDATE
An updated version of the JSFiddle demo can be found here. The update includes a new function initDomEvents() called within a then(initDomEvents) function. Despite seeing positive execution in the console, an error seems to be triggered.