首页 > 解决方案 > 如何延迟 Node/Koa 中的响应?

问题描述

我正在尝试使用 setTimeout 来延迟在 Node.js 中返回响应。使用以下代码,activateAccount api 会给出 404。它会记录“in 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)

标签: javascriptnode.jskoa

解决方案


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

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

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

PS:星号 ( *) 让我怀疑你正在使用 Koa 1,或者你已经按照关于 Koa 1 的教程进行操作。通常如果你看到*and yield,你会想要asyncandawait代替。


推荐阅读