我正在尝试使用 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)
相关分类