Using Koa
and Koa-router
, I write a function to accept POST
on /videos
and then save the video into HDFS(a distributed database). After the saving process finishing, the response should be sent to client saying that the uploading is finish. However, the response is returned before I/O finsh. I am new for JavaScript, Please help.
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()
If you are using recent versions of Koa and koa-router, then you can use async/await with Promises this way:
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/")
});
More on Promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
More on async/await: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await