Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make this JS function asynchronous?

Tags:

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

like image 318
mkrecny Avatar asked Apr 26 '11 04:04

mkrecny


2 Answers

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.

like image 126
Domenic Avatar answered Oct 11 '22 21:10

Domenic


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.

like image 31
Marc Bollinger Avatar answered Oct 11 '22 20:10

Marc Bollinger