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

前端 未结 2 414
予麋鹿
予麋鹿 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:56

    Embrace asynchronicity:

    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;
    

    Or use a promises library, or use events. In the end, they're all asynchronous callback mechanisms with slightly different semantics.

提交回复
热议问题