While creating the GUI for my project I ran into a tiny bit of a callback hell, so I will talk a little about promises and how they are useful.
While making the GUI I used jQuery for to populate the camera and lenses select boxes. The main thing about jQuery that is important for this post is that it is async; this means that the rest of the code block will run while the jQuery request is being made. In my code I have the select boxes populate and change appropriately, in order to do this I needed to use callbacks to manage this async nature.
This lead to callback hell where my callbacks needed to be nested and I ended up with the “triangle of doom.” Callback hell is suck a widely know occurrence with async javascript that there is even a website devoted just to callback hell.
There was two things I did to clean up the code a bit which included promises and making modules.
First a bit about promises. There is a really good webpage that a coworker directed me to that I will post here. It’s worth pointing out that jQuery actually has “Deferreds” these are actually a little different than promises but there is a way to cast to javascript promises with;
var thisPromise = Promise.resolve($.ajax('jsonFile.json'));
You can go to jQuery’s website to view more about Deferreds and how they can be used. For promises they can be chained together to make a sort of queue that the statements run in. This can be done with .then, I will so an basic example to make it easier to understand.
yourasynccall('jsonfile.json) .then(function(data0) { //do what you want here return anotherasycncall(data0); }) .then(function(data1) { //do more //can return a third async call here }) .catch(function(err){ //catch any error that occured });
The second thing that I did to make the code easier to read is to modularize the two parts that are async. Basically what was done is have lens and camera select separate modules
privateMethods.LensSelect = function (lensfolder) {
//the async code here with promises
};
And then in the method where the GUI is being made call the above method like so
var lensfolder = this.gui.addFolder("Lens");
privateMethods.LensSelect.call(this, lensfolder);
Using these two concepts; promises and modules my code has less chance of being spaghettied.
For the future the GUI is going to made in a different way using bootstrap so look forward to that.
Cheers,
Barbara