1

我正在使用水线 ORM 在 mongo DB 中插入新的用户数据。这是我的控制器操作中的代码。

function *(){
    var self = this;
    var attributes= this.request.body
    var userModel = this.models.user;

    userModel.create(attributes).exec(function(err, model){
        self.type = 'application/json';
        self.body = {success:true,description:"user Created"};
    });
}

当我尝试执行请求时,出现以下错误:

...../node_modules/sails-mongo/node_modules/mongodb/lib/mongodb/connection/base.js:245
    throw message;      
          ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:331:11)

我不是 Koa 的专家,但我认为这是因为这是一个异步过程,并且答案消息是之前写的。

谁能帮我??我对了解这项技术非常感兴趣。

4

1 回答 1

0

我认为这是因为这是一个异步过程,并且答案消息是之前写的。

是的。Koa 不知道查询,因此它会在查询执行完成之前继续完成响应。

您可以yield使用一个functionto Koa 来包装查询并通知它完成。

function *() {
    // ...

    yield function (done) {
        userModel.create(attributes).exec(function (err, model) {
            self.type = 'application/json';
            self.body = {success:true,description:"user Created"};
            done(err);
        });
    }
}

文档中进一步演示了此类thunk的使用,该文档基于cokoa用于thunkify生成此类函数。

于 2014-08-17T18:08:57.457 回答