在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

如何在響應(yīng)post請(qǐng)求后,服務(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....
}
}

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

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

回答
編輯回答
有點(diǎn)壞

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

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

也可以使用child_process

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

我感覺(jué)中間件就是解決你這類問(wèn)題的。
下面的代碼是koa官方提供的中間件例子,next()之后的代碼就會(huì)在請(qǐng)求返回后執(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)聽(tīng)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