javascript - 如何延迟 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)
解决方案
当 Koa 中间件函数返回时,koa 认为请求已完成,并将发送回它可以发送的内容。
但是,如果 Koa 中间件函数返回一个 Promise,它会推迟这个直到 Promise 被解决。
所以让 koa等待的诀窍是返回一个 Promise,并且只有在你完全完成后才解决这个 Promise。
PS:星号 ( *
) 让我怀疑你正在使用 Koa 1,或者你已经按照关于 Koa 1 的教程进行操作。通常如果你看到*
and yield
,你会想要async
andawait
代替。
推荐阅读
- google-ads-api - 如何使用 Google Adwords API 在多个广告系列中创建一个广告组?
- angular - 测试类扩展抽象类(Angular 5、Jasmine、Karma)
- json - 如何从获取请求中获取响应的长度?
- r - 我自己创建的函数:RemoveNA 运行一半
- linux - 在“条件变量”wait_for() notify() 机制中使用 CLOCK_MONOTONIC 类型
- html - 如何使用 BeautifulSoup / lxml 将子 DOM 节点合并/折叠到父节点?
- java - Android - WITHOUT ROWID 表的插入便捷方法返回什么值?
- c# - C# - .NET- 跨分区查询是必需的,但在我获取时被禁用
- android - Android Studio 在 Flutter 应用程序中导入 .aar 时说项目不是 gradle-build
- android - AsyncHttpClient 没有调用我的 POST API