【问题标题】:NodeJS child_process or nextTick or setTimeout for long waiting task?NodeJS child_process 或 nextTick 或 setTimeout 等待长时间的任务?
【发布时间】:2019-03-28 07:37:55
【问题描述】:

我看到了一些关于立即发送响应运行 CPU 密集型任务的问题。

我的情况是我的节点应用依赖第三方服务响应所以流程是

  1. 节点接收请求并通过第三方服务进行身份验证
  2. 身份验证后向用户发送响应
  3. 执行一些需要第三方服务响应的任务
  4. 将结果保存到数据库

在我的情况下,没有 CPU 密集型任务,不需要向用户提供额外任务的结果,但节点需要等待第三方服务的响应。身份验证后,我必须对第三方服务执行多次请求/请求才能完成任务。

我怎样才能实现这种情况?

我已经看到一些关于 child_process、nextTick 和 setTimeOut 的解决方法。

最终我想立即向用户发送响应并执行与该用户相关的任务。

提前致谢。

【问题讨论】:

  • callThirdParty(); res.send(something) 这应该在不等待的情况下调用您的第三方并 res 给用户并关闭连接,(理论上)。您尝试的一些代码可能会有所帮助
  • 我需要在发送 res.send() 之后 do_some_tasks() 而无需等待完成 do_some_tasks()

标签: node.js express asynchronous async-await node-modules


【解决方案1】:
elsewhere in your code
function do_some_tasks() { //... }

// route function
(req, res) => {
  // call some async task
  do_some_tasks()
  // if the above is doing some asynchronous task, next function should be called immediately without waiting, question is is it so?
  res.send()
}

// if your do_some_tasks() is synchronous func, the you can do
// this function call will be put to queue and executed asynchronously
setImmediate(() => {
  do_some_tasks()
})
// this will be called in the current iteration
res.send(something)

【讨论】:

    【解决方案2】:

    这里只写一个非常通用的代码块:

    var do_some_tasks = (req, tp_response) => {
        third_party_tasks(args, (err, result)=<{
            //save to DB
        });
    }
    
    var your_request_handler = (req,res) => {
        third_party_auth(args, (tp_response)=>{
            res.send();
            //just do your tasks here
            do_some_tasks(req, tp_response);
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 2023-03-26
      • 1970-01-01
      • 2013-08-06
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多