无法在KOA中设置标题使用回调时 [英] Can not set Header in KOA When using callback

查看:231
本文介绍了无法在KOA中设置标题使用回调时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在一个使用javascript回调的新项目。我使用的是 koa 框架。但是当我调用这个路由:

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) {
  var that = this;
     _OLAPSchemaProvider.LoadCubesJSon(function(result) {
    that.body = JSON.stringify(result.toString());
     });
}

我收到此错误:

_http_outgoing.js:331
throw new Error('Can\'t set headers after they are sent.');
      ^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:331:11)
at Object.module.exports.set (G:\NAP\node_modules\koa\lib\response.js:396:16)
at Object.length (G:\NAP\node_modules\koa\lib\response.js:178:10)
at Object.body (G:\NAP\node_modules\koa\lib\response.js:149:19)
at Object.body (G:\NAP\node_modules\koa\node_modules\delegates\index.js:91:31)
at G:\NAP\Server\OlapServer\index.js:42:19
at G:\NAP\Server\OlapServer\OLAPSchemaProvider.js:1599:9
at _LoadCubes.xmlaRequest.success (G:\NAP\Server\OlapServer\OLAPSchemaProvider.js:1107:13)
at Object.Xmla._requestSuccess (G:\NAP\node_modules\xmla4js\src\Xmla.js:2110:50)
at Object.ajaxOptions.complete (G:\NAP\node_modules\xmla4js\src\Xmla.js:2021:34)


推荐答案

问题是你的异步调用 LoadCubesJSon()需要一段时间才能返回,但Koa不知道并继续使用控制流。这基本上是 yield 用于。

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对象包括promise,generator和thunks。

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

我个人更喜欢使用'Q'库手动创建promise 。但您可以使用任何其他promise库或 node-thunkify 创建一个thunk。

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.

以下是 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;
}

这篇关于无法在KOA中设置标题使用回调时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆