鍍金池/ 問答/HTML/ egg 如何在響應(yīng)請求后,繼續(xù)執(zhí)行?

egg 如何在響應(yīng)請求后,繼續(xù)執(zhí)行?

如何在響應(yīng)post請求后,服務(wù)端繼續(xù)執(zhí)行代碼?

{
    id: 1
    data: 2
}

* abc(){
const ctx = this.ctx;
const result = yield this.ctx.service.bcd();
ctx.body = {result.data};

if(result.id){
todo....
}
}

這段代碼會在執(zhí)行完if后才發(fā)送body的響應(yīng)內(nèi)容

該怎么寫讓請求先被響應(yīng),然后繼續(xù)執(zhí)行if?

回答
編輯回答
有點壞

為什么要這樣操作呢,你后面的操作如果不成功會對之前的response有影響么,
如果你只是單純的想在請求中"異步"執(zhí)行一些操作,可以參考一下app.runInBackground

2017年12月8日 02:36
編輯回答
吃藕丑

也可以使用child_process

2018年4月28日 02:22
編輯回答
尤禮

我感覺中間件就是解決你這類問題的。
下面的代碼是koa官方提供的中間件例子,next()之后的代碼就會在請求返回后執(zhí)行。

async function responseTime(ctx, next) {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
}

app.use(responseTime);

查看官方指南===>
https://github.com/koajs/koa/...

2017年9月11日 01:53
編輯回答
逗婦惱

事件

const Emitter = require('events').EventEmitter
const emitter = new Emitter()

if(result._id) {
  emitter.emit('data', result._id)
}

ctx.body = { result.data }

在別的地方監(jiān)聽data事件

emitter.on(data', (data) => {
   todo....
})
2018年2月3日 21:54
編輯回答
假灑脫

* abc(){
const ctx = this.ctx;
const result = yield this.ctx.service.bcd();
ctx.body = {result.data};

process.nextTick(()=>{
if(result.id){
todo....
}
})
}
2017年3月6日 17:44