JavaScript, Node.js: is Array.forEach asynchronous?

后端 未结 10 1585
时光说笑
时光说笑 2020-11-22 10:47

I have a question regarding the native Array.forEach implementation of JavaScript: Does it behave asynchronously? For example, if I call:

[many          


        
10条回答
  •  -上瘾入骨i
    2020-11-22 11:47

    There is a common pattern for doing a really heavy computation in Node that may be applicable to you...

    Node is single-threaded (as a deliberate design choice, see What is Node.js?); this means that it can only utilize a single core. Modern boxes have 8, 16, or even more cores, so this could leave 90+% of the machine idle. The common pattern for a REST service is to fire up one node process per core, and put these behind a local load balancer like http://nginx.org/.

    Forking a child - For what you are trying to do, there is another common pattern, forking off a child process to do the heavy lifting. The upside is that the child process can do heavy computation in the background while your parent process is responsive to other events. The catch is that you can't / shouldn't share memory with this child process (not without a LOT of contortions and some native code); you have to pass messages. This will work beautifully if the size of your input and output data is small compared to the computation that must be performed. You can even fire up a child node.js process and use the same code you were using previously.

    For example:

    var child_process = require('child_process');
    function run_in_child(array, cb) {
        var process = child_process.exec('node libfn.js', function(err, stdout, stderr) {
            var output = JSON.parse(stdout);
            cb(err, output);
        });
        process.stdin.write(JSON.stringify(array), 'utf8');
        process.stdin.end();
    }
    

提交回复
热议问题