JosepB
JosepB

Reputation: 2315

Javascript for-loop async File execution

In the next code, I want to process several files at the same time without wait to the end of each other. For this reason, I first read the files (array) and then the callback is called to process an element of this array instance.

I have found a problem into this javascript code, exactly in a async for-loop, where this process is executed as a sync code instead of async.

var array = ['string1','string2','string3','string4'];

function processArray (arrayString,callback){
    //Read file Example.csv thought sync way
    try{
        var ifs = new InputFileStream('Example.csv','utf8');
        table = ifs.read(0);
        ifs.close();
    }catch(err){
        console.log(err.stack);
    }

    callback(arrayString, table);

}

//Async for
for (var i=0; i<array.length; i++) {                
    processArray(array[i], function(arrayString, table){
        //Here process the file values thought async way
        console.log('processed_'+i);
    });
}   

Upvotes: 0

Views: 86

Answers (2)

Fernando Carvajal
Fernando Carvajal

Reputation: 1945

where this process is executed as a sync code instead of async

I've seen that you just have find out the answers of your question, remember that JavaScript is single thread.

So, for that when you execute operations that require full use of CPU like for..loops, while, etc; you just will get your code running synchronous and not only that,

You will get your web page freeze if they are huge loops

Let me give you an example, this is a while loop that will run for 6 seconds, look how you cannot do anything in stackoverflow.

function blocker (ms) {
    console.log('You cannot do anything')
    var now = new Date().getTime();
    while(true) {
        if (new Date().getTime() > now +ms)
            return;
    }   
}
blocker(6000) //This stop your entire web page for 6 seconds

If you really want to achieve running blocking code in the background read about Web Workers or you just can use a small library I wrote, that allow you to execute a blocking CPU function in the background, I called it GenericWebWorker

Upvotes: 0

bhspencer
bhspencer

Reputation: 13560

You could put the call back in a setTimeout with a delay of 1ms. That will run it in the next block of execution and your loop will continue on.

e.g. use this:

setTimeout(function() { callback(arrayString, table); }, 1);

instead of this:

callback(arrayString, table);

An alternative to this is to run the callback on a separate thread using Web Workers. I don't think it would appropiate to provide a long answer describing how to do multi threaded JavaScript here so I'll just leave the link to the docs. https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

Upvotes: 1

Related Questions