【发布时间】: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