How to wait for function to finish before continuning in Node.js

前端 未结 2 419
予麋鹿
予麋鹿 2020-12-17 03:10

I am trying to create a route in Node.js/Express that reads data from two queries and then increments a count based on that data from the queires. Since Node.js is asynchro

2条回答
  •  星月不相逢
    2020-12-17 03:55

    You can use some library like async.

    Here is the code:

    var total = 0;
    /* GET users listing. */
    router.get('/', function(req, res) {
        async.series([
                function(callback){
                    increment(2, function(){
                        callback(null, "done");
                    });
                },
                function(callback){
                    increment(3, function(){
                        callback(null, "done");
                    });
                }
            ],
            function(err, result){
                console.log(total);
                res.send('respond the result:' + total);
            });
    });
    
    var increment = function(n, callback){
        //Wait for n seconds before incrementing total n times
        setTimeout(function(){
            for(var i = 0; i < n; i++){
                total++;
            }
            callback();
        }, n *1000);
    };
    

提交回复
热议问题