如何在Koa-router中完成数据库I / O后返回响应?

时间:2017-06-15 07:46:43

标签: javascript node.js koa koa-router

使用KoaKoa-router,我在POST上编写了一个接受/videos的函数,然后将视频保存到HDFS(分布式数据库)中。保存过程结束后,应将响应发送给客户端,说明上传完成。但是,在I / O finsh之前返回响应。我是JavaScript新手,请帮助。

app.js:

/**
 * Module dependencies.
 */

const logger = require('koa-logger');
const serve = require('koa-static');
const koaBody = require('koa-body');
const Koa = require('koa');
const app = new Koa();
const os = require('os');
const path = require('path');
var Router = require('koa-router');

var router = new Router();
// log requests

app.use(logger());

app.use(koaBody({ multipart: true }));

app.use(serve(path.join(__dirname, '/public')));



app
  .use(router.routes())
  .use(router.allowedMethods());

// listen

app.listen(3000);
console.log('listening on port 3000');



module.exports ={
  app:app,
router:router
} 

require('./services/service_upload.js')

service_upload.js

const router = require('../app.js').router

const upload = require('../business/business_uploadVideo.js')
 function service_upload() {
    router.post('/videos', function (ctx, next) {
        upload.upload(ctx, function () {
        })


        ctx.body='upload finish'
        console.log("redirect/")

    });
}


service_upload()

1 个答案:

答案 0 :(得分:0)

如果您使用的是最近版本的Koa和koa-router,那么您可以通过承诺以这种方式使用 async / await

WHERE
      EJEM.EJ_tran_event_id = '5011' --SignOn
 AND  EJEM.EJ_tran_event_id = '5119' --Reinit Printer
 AND EJEM.EJ_tran_event_id = '5101' --NoSale                        
 AND
 EJTM.event_date_time between '2017-06-06 03:00:00.000' and '2017-06-08 03:00:00.000'
 AND
 EJEM.language_id = 'EN-US'

更多关于承诺:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

有关async / await的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await