NodeJS child_process或nextTick或setTimeout用于长时间等待任务?

问题描述 投票:0回答:2

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

我的情况是我的节点应用程序依赖于第三方服务响应,因此流程是

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

在我的情况下,没有CPU密集型任务,也不需要向用户提供额外任务的结果,但节点需要等待来自第三方服务的响应。在完成任务后,我必须在第三方服务之后对第三方服务执行多次req / res。

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

我见过一些关于child_process,nextTick和setTimeOut的变通方法。

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

提前致谢。

node.js express asynchronous async-await node-modules
2个回答
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)

0
投票

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

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);
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.