0

For example:

var array = ['A','B','C','D','E','A','B','C','D','E','A','B','C','D','E'];

function test(cb) {
    var newArray = [];
    for (var i = 0; i < array.length; i++) {
         newArray.push(array[i]);
    }
    cb(newArray);
}

test(function (data) {
    console.log(data);     
});

console.log('test');

http://jsfiddle.net/7sz7Ldoa/

Let's say that the array has millions of values. It will take long for the newArray to get populated, and meanwhile my other code (console.log) isn't running.

Why isn't it async by default like a lot of things are in JS?

How can I make it more efficient by making it async?

Dan P.
  • 1,707
  • 4
  • 29
  • 57
  • Break it up into asynchronous batches by using `setTimeout` or `setInterval`. – cookie monster Aug 16 '14 at 00:18
  • How to make it work asynchronously so the console.log runs before the for loop is done? – Dan P. Aug 16 '14 at 00:18
  • Seems like setTimeout or setInterval would slow down the program though. If the console.log was replaced by something that for example shows an image on a web page, it wouldn't be most efficient either. – Dan P. Aug 16 '14 at 00:20
  • Batches. If you have a million, then maybe do 10,000 at a time. It's all up to you, but if you want it to be async, then you need to make it async by using built-in async constructs like `setTimeout`. – cookie monster Aug 16 '14 at 00:21
  • To answer your title more directly, code is always simplest and easiest to comprehend when you can know that it will run in the order in which it's written. If everything was async, it would be a headache to manage. There is a new language called [ParaSail](https://forge.open-do.org/plugins/moinmoin/parasail/) where it's basically making everything async (multi-threaded) by default. I believe it's still in the experimental stage though – cookie monster Aug 16 '14 at 00:25
  • @cookiemonster is right, you have to do it in batches that way you don't block the event loop – Miguel Mota Aug 16 '14 at 00:26
  • In most cases loading millions of values into array in the memory isnt a good practice. I dont quite get what you meant asking this question so it is hard for me to answer. What else other than executing code using `setInterval`, `setTimeout`, xmlhttp requests and external event handling is asynchronous? If running `for` loop was asynchronous I suppose it would break the control flow and make it a lot harder to control logic without using some form of mutual exclusion abstraction. – Boris D. Teoharov Aug 16 '14 at 00:28
  • Async is not inherently more efficient. – Matt Ball Aug 16 '14 at 00:36

0 Answers0