문제

최근에 JavaScript 콜백을 사용하는 새로운 프로젝트에서 일했습니다.그리고 KOA 프레임 워크를 사용하고있었습니다.그러나 내가이 경로를 호출했을 때 :

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)
.

도움이 되었습니까?

해결책

문제는 Async 호출 LoadCubesJSon()가 잠시 반환하는 데 시간이 걸리지 만 KOA는 그렇게 알지 못하고 제어 흐름으로 계속됩니다.기본적으로 yield가있는 것입니다.

"ayledable"객체에는 약속, 발전기 및 썽크 (다른 것들 중)가 포함됩니다.

개인적으로 'q'라이브러리를 사용하여 수동으로 약속을 만드는 것을 선호합니다 .그러나 당신은 다른 약속 도서관이나 node-thunkify 을 사용하여 썽크를 만들 수 있습니다.

여기서는 짧지 만 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);
.

코드는 다음과 같이 보입니다.

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;
}
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top