【问题标题】:nodejs multi threading async parallelnodejs多线程异步并行
【发布时间】:2017-09-20 19:39:42
【问题描述】:

目前我有一个仪表板,其中列出了表中的一堆记录。用户可以选择 1 条记录并点击执行,然后我向我的路由中间件发送 AJAX POST 请求,该中间件在 async.waterfall 中执行 3 个函数,如果一切正常,则向我的客户端返回 200 响应。这个异步瀑布通常需要大约 40-55 秒才能完成执行(fn_1、fn_2 和 fn_3)并且运行良好。

router.post('/url', function(req, res, next) {
    try {
        async.waterfall([
            fn_1,
            fn_2,
            fn_3
        ], function (err, body) {
            res.writeHead(200, {'Content-Type': 'application/json'});
            res.end(JSON.stringify({"error":err, "result":body}));
        });
        function fn_1(callback) {
                    callback(null, response);
        }
        function fn_1(result, callback) {

                callback(err, result);

        }
        function fn_2(result, callback) {

                callback(null, result);

        }

    }
    catch (err){
        console.log(err)
    }

});

但是,如果我要让用户选择 MULTIPLE 记录并将其作为数组发送回我的路由中间件。我如何为数组中的每个项目执行多个 async.waterfall 方法并行

我可以运行一个循环并在循环内执行瀑布,但它会再次等待每个项目完成,然后才开始下一次迭代。这不是我想要的。

这在 node / express 中可行吗?实现这一目标的最简单方法是什么?还是有可以帮助解决这种情况的模块/插件?

【问题讨论】:

  • 看看 npm package 'cluster'

标签: node.js ajax multithreading express asynchronous


【解决方案1】:

这里是您的代码的缩写版本,以及如何根据您的需要对其进行更改。如果您的任何调用都不需要来自任何其他调用的数据,您可以将它们与 Promise 并行运行并使用 Promise.all 来捕获结果。

function fn_1(callback) {
  // See function fn_2 for structure
}
function fn_1(result, callback) {

  // See function fn_2 for structure

}
function fn_2(result, callback) {

  return new Promise(resolve, reject => {
    resolve(result)
  })
  .then(d => {
    // Instead of callbacks, use a "then" 
    // block/statement.
    //
    // Do something with D here.
  })

}

Promise.all([fn_1(), fn_2(), fn_3()])
  .then(v => {
    // Do somthing with v;
  })
  .catch(e => {
    // Do something with e
  })

【讨论】:

    【解决方案2】:

    我倾向于提倡使用原生 Promises 而不是像 async 这样的库,但是,因为您已经在使用 async...

    您可以使用 parallel 并将数组中的每个项目映射到瀑布处理程序,例如

    async.parallel(
        myArray.map(val => cb => async.waterfall(fn_1, fn_2, fn_3, cb)
    , (err, results) => {
        // return consolidated response
    })
    

    您需要重新设计瀑布处理程序以不发送响应,而只是传播任何错误。

    还应该注意的是,并行仅在您实际上运行 I/O 绑定代码时才有用,如果代码与您的示例类似,那么您将不会真正从使用并行而不是像 async.each 之类的东西中获得任何好处

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 2018-12-01
      • 2013-03-16
      • 1970-01-01
      相关资源
      最近更新 更多