0

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

应用程序.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')

服务上传.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()
4

1 回答 1

0

如果您使用的是最新版本的 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/")
    });

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

更多关于异步/等待:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

于 2017-06-15T07:56:34.587 回答