Add intentional latency in express

后端 未结 7 2095
暖寄归人
暖寄归人 2020-12-29 18:37

Im using express with node.js, and testing certain routes. I\'m doing this tute at http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 19:10

    You could also just write your own generic delay handler using a Promise or callback (using a q promise in this case):

    pause.js:

    var q = require('q');
    
    function pause(time) {
        var deferred = q.defer();
    
        // if the supplied time value is not a number, 
        // set it to 0, 
        // else use supplied value
        time = isNaN(time) ? 0 : time;
    
        // Logging that this function has been called, 
        // just in case you forgot about a pause() you added somewhere, 
        // and you think your code is just running super-slow :)
        console.log('pause()-ing for ' + time + ' milliseconds');
    
        setTimeout(function () {
            deferred.resolve();
        }, time);
    
        return deferred.promise;
    }
    
    module.exports = pause;
    

    then use it however you'd like:

    server.js:

    var pause = require('./pause');
    
    router.get('/items', function (req, res) {
        var items = [];
    
        pause(2000)
            .then(function () {
                res.send(items)
            });
    
    });
    

提交回复
热议问题