如何在数据库 I/O 完成后在 Koa-router 中进行 return 响应?

How to return response after database I/O finish in Koa-router?

使用 KoaKoa-router,我编写了一个函数来接受 POST on /videos,然后将视频保存到 HDFS(分布式数据库)中。保存过程完成后,应将响应发送给客户端,说明上传已完成。但是,响应在 I/O 完成之前返回。我是 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()

如果您使用的是最新版本的 Koa 和 koa-router,那么您可以使用 async/awaitPromises 这个方式:

    router.post('/videos', async function (ctx, next) { // Declare function as async
      await new Promise((resolve, reject) => { // Create new Promise, await will wait until it resolves
        upload.upload(ctx, function (error) {
          if (error) { // Probably you should do error handling
            reject(error);
            return;
          }

          resolve();
        })
      });

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

关于 Promise 的更多信息: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