49

node.js で Express を使用し、特定のルートをテストしています。私はhttp://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/でこのチュートを行っています

経由で ajaxを呼び出してhttp://localhost:3000/winesいます (内容は関係ありません)。しかし、レイテンシーをテストしたいです。2秒後にエクスプレス応答させるようなことはできますか? (私は ajax ローダーをシミュレートしたいのですが、localhost で実行しているので、待ち時間はほとんどありません)

4

8 に答える 8

94

すべてのリクエストに対してミドルウェアとして使用

  app.use(function(req,res,next){setTimeout(next,1000)});
于 2013-11-13T13:22:36.323 に答える
61

setTimeoutres.send内で呼び出すだけです:

setTimeout((() => {
  res.send(items)
}), 2000)
于 2013-02-06T21:21:10.197 に答える
5

connect-pauseモジュールを試してください。アプリのすべてのルートまたは一部のルートのみに遅延が追加されます。

于 2013-09-06T07:31:55.117 に答える
1

Promise またはコールバック (この場合はq promise を使用) を使用して、独自の一般的な遅延ハンドラーを作成することもできます。

一時停止.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;

その後、好きなように使用してください:

サーバー.js:

var pause = require('./pause');

router.get('/items', function (req, res) {
    var items = [];

    pause(2000)
        .then(function () {
            res.send(items)
        });

});
于 2016-08-13T08:31:42.587 に答える