如何在Node / Koa中延迟响应?
我正在尝试使用setTimeout延迟在Node中返回响应。使用以下代码,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 {}
}
回答如下:当Koa中间件函数返回时,koa认为请求done并将发回它可以的内容。
但是,如果Koa中间件函数返回了一个承诺,它将推迟到承诺被解决为止。
所以让koa wait的诀窍是返回承诺,并且仅在完全完成后才解决承诺。
PS:星号(*
)使我怀疑您正在使用Koa 1,或者您已阅读了有关Koa 1的教程。通常,如果看到*
和yield
,则需要async
和改为await
。