简体   繁体   中英

node.js waiting for callbacks

I am trying to grasp the flow control of node.js. In my code below I defined a function, which contains a recursive function. I want to call this "main" function, wait for it to be done completely and console.log the result. The problem is the non-blocking way of node.js. How do I have to set the callbacks to ensure, the output is correct?

In the code below the output will be empty, how do I change this? As far as I can see, I have to set a callback, but all my efforts so far where useless.

var main = function(){

    var list=[1,2,3,4];
    var value=[];

    function twotimes(i){
        if (i<list.length){
            var j=i*2;
            value[i]=j;
            twotimes(i+1); //recursive call of "twotimes"
        }
    }
    twotimes(0); //initiate the function
}

main(function(err){
console.log(value);
});

try this:

var main = function(callback){
    var list=[1,2,3,4];
    var value=[];
    function twotimes(i){
        if (i<list.length){
            var j=i*2;
            value[i]=j;
            twotimes(i+1); //recursive call of "twotimes"
        }
    }
    twotimes(0); //initiate the function
    callback(value) 
}

main(function(value){
    console.log(value);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM