0
function nodeSearch(path) {
    lookup.getChildrenAsCallback(path, function(err, nodesFromCb) {
                if (nodesFromCb.length > 0) {
                    for (var i = 0; i < nodesFromCb.length; i++) {
                        console.log("i", i);
                            nodesFrom.push(path + "/" + nodesFromCb[i]);
                                lookup.getChildrenAsPromise(path + "/" + nodesFromCb[i])    
                                      .then(function(nodesFromPromise) {
                                            nodesFrom.push(path + "/" + nodesFromCb[i] + "/" + nodesFromPromise[0]);
                                            nodeSearch(path + "/" + nodesFromCb[i] + "/" + nodesFromPromise[0]);
                                      });


                    }
                } else {
                    return;
                }
            });
}       

My intention was to function nodeSearch call itself again in a for loop after getting the result from promise.But now for loop executes continuously without waiting for the result from the promise. I am not sure how to use promise in these scenario could someone please help. Thanks in advance.

rajmohan
  • 1,618
  • 1
  • 15
  • 36

1 Answers1

0

you could build this as follows:

//just promisifying `lookup.getChildrenAsCallback`
function getChildrenAsPromise(path){
    return new Promise(function(resolve, reject){
        lookup.getChildrenAsCallback(path, function(err, children) {
            if(err) reject(err); 
            else resolve(children);
        });
    })
}

//basically the resucrive version of `getChildrenAsPromise`
function nodeSearch(path) {
    //get the direct children for this path
    return getChildrenAsPromise(path)
        //then run the recursion, get their descendants
        .then(function(nodes){
            return Promise.all(nodes.map(function(node){
                //the recursive part
                return nodeSearch(path + "/" + node);
            }))
        })
        //then flatten the result and prepend the current path
        .then(function(children){
            //children is actually an array of arrays
            //so we need to flatten it.
            var p = [ path ];
            return p.concat.apply(p, children);
        });
}

anything unclear?

Thomas
  • 11,958
  • 1
  • 14
  • 23