Koa: ctx wasn't able to return after set in other callback function

Created on 21 Apr 2016  路  4Comments  路  Source: koajs/koa

I used the below code, the last line doesn't work in callback function of getall. there is no any response was return.

router.get('/',function (ctx, next) {
getall(function(result){
console.log('result===>',result);
ctx.body=result;
}
}
but I move the last line in out of the getall, it may return a response correctly.

question

Most helpful comment

koa send http response immediately when sync middleware called.
If there has async code in the middleware, the middleware should be async function or return a Promise

All 4 comments

router.get('/', function(ctx, next) {
    return new Promise(function(resolve, reject) {
        getall(function(result) {
            console.log('result===>', result);
            ctx.body = result;
            resolve();
        })
    });
})

koa send http response immediately when sync middleware called.
If there has async code in the middleware, the middleware should be async function or return a Promise

as @liangxingchen stated, you aren't doing control flow properly. middleware should always be returning a promise in koa v2

Yes, it works. Thanks

Was this page helpful?
0 / 5 - 0 ratings