快速添加有意图的延迟

我使用express与node.js,并testing某些路线。 我正在通过http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/

我通过ajax调用http://localhost:3000/wines (内容无关紧要)。 但是我想testing延迟。 我可以在2秒后做一些快速回应吗? (我想模拟ajax加载器,我在本地运行,所以我的延迟几乎为零)

只需在setTimeout中调用res.send

 setTimeout((function() {res.send(items)}), 2000); 

用作中间件,用于您的所有请求

  app.use(function(req,res,next){setTimeout(next,1000)}); 

尝试连接暂停模块。 它会在您的应用中添加全部或部分路由。

要在全局请求中应用全局请求,可以使用以下代码:

 app.use( ( req, res, next ) => { setTimeout(next, Math.floor( ( Math.random() * 2000 ) + 100 ) ); }); 

时间值是:

最大值= 2000(最小值增加,因此实际上是2100)

最小= 100

你也可以使用Promise或callback(在这种情况下使用q promise)来编写自己的通用延迟处理程序:

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; 

然后使用它,但是你想要:

server.js:

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