How to apply bluebird promises to my existing javascript traversal and recursive based logic?
<p>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:</p>

<p>In my web application on page load using jQuery, I will get page's main menu links and generate a <a href="http://jnuno.com/tree-model-js/" rel="nofollow noreferrer">TreeModel</a> structure from them which I will use later on to show a Breadcrumb on page top.</p>

<p>The function I am using for generating this TreeModel is following:</p>

<pre><code>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 &gt; 0;
        if (hasChildren == true)
            _traverseNodeChildren.apply(this.comp, ["+ul.dropdown-menu &gt; li &gt; a", node, callback1, callback2]);

        if (node.model.id == "aboutLink") // last node
        {
            setTimeout(() =&gt; {
                callback1.apply(this.comp, [callback2]);
            }, 100);
        }
    }.bind({parentNode: parentNode, comp: this}));
}
</code></pre>

<p>After above traversal completes, I want to call <code>myServerCall</code> function that will involve an async Ajax request and post to completion of this async request, finally I want to call a third function <code>myFinalFunc</code>.</p>

<p>At present I am using following code to make this traversal code execute:</p>

<pre><code>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, ["&gt; li &gt; a[data-bc-id]", 
            _bcRoot, myServerCall, myFinalFunc]);
</code></pre>

<p>But I would like it to be converted to bluebird promise based approach to get more control over it.</p>

<p>Following is the code that I want like it to be in the end: </p>

<pre><code>_traverseNodeChildren.apply(this, ["&gt; li &gt; a[data-bc-id]", _bcRoot])
    .then(function() {
        return myServerCall();
    })
    .then(function() {
        return myFinalFunc();
    })
    .catch(function(error) {

    });
</code></pre>

<p>How can I do this using bluebird?</p>