I am curious to know how can I make use of bluebird promises in my existing javascript code that makes use of lots of callback based mechanism. Here is the scenario:
In my web application on page load using jQuery, I will get page's main menu links and generate a TreeModel structure from them which I will use later on to show a Breadcrumb on page top.
The function I am using for generating this TreeModel is following:
function _traverseNodeChildren(selector, parentNode, callback1, callback2) {
$(parentNode.model.element).find(selector).each(function(idx, elm) {
// Create a Tree Node using TreeModel
let node = _createTreeNode.apply(this.comp, [elm]);
this.parentNode.addChild(node);
let hasChildren = $(elm).find("+ul.dropdown-menu").length > 0;
if (hasChildren == true)
_traverseNodeChildren.apply(this.comp, ["+ul.dropdown-menu > li > a", node, callback1, callback2]);
if (node.model.id == "aboutLink") // last node
{
setTimeout(() => {
callback1.apply(this.comp, [callback2]);
}, 100);
}
}.bind({parentNode: parentNode, comp: this}));
}
After above traversal completes, I want to call myServerCall
function that will involve an async Ajax request and post to completion of this async request, finally I want to call a third function myFinalFunc
.
At present I am using following code to make this traversal code execute:
const TreeModel = require('tree-model');
const _treeModel = new TreeModel();
let _bcRoot = _treeModel.parse({
id: "0",
href: null,
text: "",
element: $(".main-menu").get(0)
});
_traverseNodeChildren.apply(this, ["> li > a[data-bc-id]",
_bcRoot, myServerCall, myFinalFunc]);
But I would like it to be converted to bluebird promise based approach to get more control over it.
Following is the code that I want like it to be in the end:
_traverseNodeChildren.apply(this, ["> li > a[data-bc-id]", _bcRoot])
.then(function() {
return myServerCall();
})
.then(function() {
return myFinalFunc();
})
.catch(function(error) {
});
How can I do this using bluebird?