How to wait for a function to finish before moving to Node.js

I am trying to create a route in Node.js / Express that reads data from two requests and then increases the score based on this data from countries. Since Node.js is asynchronous, my total amount is displayed before all data is read.

I created a simple example that goes as far as what I'm doing right now

var express = require('express');
var router = express.Router();


var total = 0;

/* GET home page. */
router.get('/', function(req, res, next) {
  increment(3);
  increment(2);
  console.log(total);
  res.end();
});



var increment = function(n){
    //Wait for n seconds before incrementing total n times
    setTimeout(function(){
    for(i = 0; i < n; i++){
        total++;
    }   
    }, n *1000);
};
module.exports = router;

I'm not sure what I will need to do to wait until both functions finish before I print the result. Should I create a custom Event Emitter to achieve this?

+4
source share
2 answers

Declare asynchrony:

var express = require('express');
var router = express.Router();


var total = 0;

/* GET home page. */
router.get('/', function(req, res, next) {
  increment(3, function() {                 // <=== Use callbacks
      increment(2, function() {
          console.log(total);
          res.end();
      });
  });
});



var increment = function(n, callback){    // <=== Accept callback
    //Wait for n seconds before incrementing total n times
    setTimeout(function(){
        for(i = 0; i < n; i++){
            total++;
        }   
        callback();                        // <=== Call callback
    }, n *1000);
};
module.exports = router;

promises . , .

+9

, async.

:

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);
};
+2

All Articles