Recently I worked on a new project that used javascript callbacks. And I was using koa framework. But when I called this route :
function * getCubes(next) {
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;
}