【问题标题】:How to delay response in Node/Koa?如何延迟 Node/Koa 中的响应?
【发布时间】:2019-09-25 16:39:33
【问题描述】:

我正在尝试使用 setTimeout 来延迟在 Node.js 中返回响应。使用以下代码,activateAccount api 会给出 404。它会记录“在 setTimeout”中,但不会返回任何内容。有没有办法做到这一点?

module.exports.activateAccount = function *() {
    this.body = { ok: false };

    if(this.session.otherMembershipFound){
        console.log("in otherMembershipFound");
        setTimeout(function() {
            console.log("in setTimeout");
            this.status = 200;
            this.body = { ok: false, result: { 
                    ok: false
                    , result: null
                    , message: "We encountered one or more validation errors."
                    , debug: "Other Membership Found"
                } 
            };
        }, 3000)    
    } else {}
}

根据下面的 Promise 解释,我尝试了以下方法,但我正在为正确的实现应该是什么而苦苦挣扎。

if(this.session.otherMembershipFound){
    console.log("in otherMembershipFound");
    return new Promise(resolve => {
        setTimeout(resolve, 3000);
      })
      .then(() => {
        console.log("after");
        this.status = 200;
        this.body = { ok: false, result: { 
                ok: false
                , result: null
                , message: "We encountered one or more validation errors. Please check the entered data and try again. For assistance please call 1 (800)617-3169."
                , debug: "Other Membership Found"
            } 
        };
    }, 3000)    
} else {

我得到这个错误

(node:21796) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client
at ServerResponse.removeHeader (_http_outgoing.js:540:11)

【问题讨论】:

    标签: javascript node.js koa


    【解决方案1】:

    当 Koa 中间件函数返回时,koa 会认为请求完成,并会发回它可以发送的内容。

    但是,如果 Koa 中间件函数返回一个 Promise,它会推迟这个直到 Promise 被解决。

    所以让 koawait 的诀窍是返回一个 Promise,并且只有在你完全完成后才解决这个 Promise。

    await 代替。

    【讨论】:

    • 你能帮我看看这个语法吗?
    • 您的代码是朝着正确方向迈出的一步,但this.status 可能没有意义。你的ctx 参数在哪里? statusbody 之类的东西通常设置在 ctxctx.response 上。
    • 我们使用的是不使用 ctx 的旧版 Koa。我们需要更新它,但还没有到那里。
    • 我想即使是 Koa 1 也会有这个。如果没有,恐怕我帮不了你。我只是对旧版本不够熟悉。
    【解决方案2】:

    您可以使用 koa-delay 库来完成这项工作。 https://www.npmjs.com/package/koa-delay 遵循图书馆页面中的文档。

    【讨论】:

    • 我试过了,它没有破坏任何东西,但它根本没有延迟。响应仍然立即返回。
    猜你喜欢
    • 1970-01-01
    • 2019-08-01
    • 2015-01-02
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    相关资源
    最近更新 更多