5

応答遅延を最適化するには、応答がクライアントに返されたに作業を実行する必要があります。ただし、応答が送信された後にコードを実行できるように見える唯一の方法は、setTimeout. より良い方法はありますか?おそらく、応答が送信された後にコードをプラグインする場所、またはコードを非同期的に実行する場所でしょうか?

ここにいくつかのコードがあります。

koa                  = require 'koa'
router               = require 'koa-router'

app = koa()

# routing
app.use router app

app
  .get '/mypath', (next) ->
    # ...
    console.log 'Sending response'

    yield next

    # send response???

    console.log 'Do some more work that the response shouldn\'t wait for'
4

3 に答える 3

0

私も同じ問題を抱えてる。

koa は、すべてのミドルウェアが終了した場合にのみ応答を終了します ( application.jsでは、respondは応答ミドルウェアであり、応答を終了します。)

app.callback = function(){
  var mw = [respond].concat(this.middleware);
  var gen = compose(mw);
  var fn = co.wrap(gen);
  var self = this;

  if (!this.listeners('error').length) this.on('error', this.onerror);

  return function(req, res){
    res.statusCode = 404;
    var ctx = self.createContext(req, res);
    onFinished(res, ctx.onerror);
    fn.call(ctx).catch(ctx.onerror);
  }
};

response.endしかし、ノードの API である関数を呼び出すことで問題を解決できます。

exports.endResponseEarly = function*(next){
    var res = this.res;
    var body = this.body;

    if(res && body){
        body = JSON.stringify(body);
        this.length = Buffer.byteLength(body);
        res.end(body);
    }

    yield* next;
};
于 2015-03-20T09:32:10.653 に答える
-3

setTimeout次のように、use を使用して非同期タスクでコードを実行できます。

 exports.invoke = function*() {
  setTimeout(function(){
    co(function*(){
      yield doSomeTask();
    });
  },100);
  this.body = 'ok';
};
于 2016-12-20T08:15:40.523 に答える