Can not set Header in KOA When using callback

谁都会走 提交于 2019-12-01 08:28:25

The problem is that your async call LoadCubesJSon() takes a while to return but Koa isn't aware of that and continues with the control flow. That's basically what yield is for.

"Yieldable" objects include promises, generators and thunks (among others).

I personally prefer to manually create a promise with the 'Q' library. But you can use any other promise library or node-thunkify to create a thunk.

Here is short but working example with Q:

var koa = require('koa');
var q = require('q');
var app = koa();

app.use(function *() {
    // We manually create a promise first.
    var deferred = q.defer();

    // setTimeout simulates an async call.
    // Inside the traditional callback we would then resolve the promise with the callback return value.
    setTimeout(function () {
        deferred.resolve('Hello World');
    }, 1000);

    // Meanwhile, we return the promise to yield for.
    this.body = yield deferred.promise;
});

app.listen(3000);

So your code would look as follows:

function * getCubes(next) {
    var deferred = q.defer();

    _OLAPSchemaProvider.LoadCubesJSon(function (result) {
        var output = JSON.stringify(result.toString());
        deferred.resolve(output);
    });

    this.body = yield deferred.promise;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!