为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Node/Koa 中延迟响应?

如何在 Node/Koa 中延迟响应?

互换的青春 2021-10-29 10:32:28
我正在尝试使用 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 clientat ServerResponse.removeHeader (_http_outgoing.js:540:11)
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 272 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信