开发者

How do I make this JS function asynchronous?

开发者 https://www.devze.com 2023-02-28 12:43 出处:网络
function takesTime(){ for (var i = 0; i<some_very_large_number; i++){ //do something synchronous } console.log(\'a\');
function takesTime(){

    for (var i = 0; i<some_very_large_number; i++){
        //do something synchronous
    }
    console.log('a');
}

takesTime();
console.log('b'开发者_高级运维);

This prints: a b How would you make it print: b a


for (var i = 0; i < someVeryLargeNumber; ++i) {
    setTimeout(function () {
        //do something synchronous
    }, 0);
}

Also see setZeroTimeout to gain a few milliseconds each loop, although the work people are doing there seems to be browser-based.


I see this is tagged node.js, so I'll answer it from that perspective: you shouldn't. Usually, if you're blocking, it will be: network-bound (you should be using and/or reusing network libraries around asynchronous methods), I/O-bound (you should be using and/or reusing I/O libraries), or CPU-bound. You haven't provided any context for what the long-running task is, and given that you have a loop invariant containing some_very_large_number, I'm assuming you're imagining some CPU-intensive task iterating over a large field.

If you're actually CPU-bound, you should rethink your strategy. Node only lives on one core, so even if you were able to use multithreading, you'd really just be spinning your wheels, as each request would still require a certain amount of CPU time. If you actually intend on doing something computationally-intensive, you may want to look into using a queuing system, and having something else processing the data that's better designed for crunching it.


Javascript is event-based, and everything happens in a single thread. The way for you to make it "asynchronous" is to use a timeout (setTimeout()).


You can use web workers to achieve your objective, but you'll require a separate js file, and you'll have to add plumbing code to post messages and handle those messages.

node.js doesn't support web workers natively, but an implementation is available at:

https://github.com/cramforce/node-worker/

Otherwise, it's similar to the following code:

var pid = require('child_process').spawn('node', ['childScript.js'])
pid.stdout.on('data', function(data) {
  console.log(data);
});
console.log('b');

childScript.js

for (var i = 0; i < some_very_large_number; i++) {
  // do something synchronous
}
console.log('a');
0

精彩评论

暂无评论...
验证码 换一张
取 消