Skip to content Skip to sidebar Skip to footer

Asynchronous Execution In Javascript Any Solution To Control Execution?

I need a solution to control code execution in javascript.I want code on next line should not be executed unless the code on current line is completely executed. Is there any solut

Solution 1:

The issue is that loadend is running as soon as any one of the FileReaders has completed loading. You'll need to redesign the code to wait for all 3 of them to finish, something like:

functionhandleFileSelect(evt) {    
    var files = evt.target.files;    
    var fileReaders = [];
    var loadCount = 0;

    for (var i = 0; i < files.length; i++) {
        f = files[i];
        fileExtension = f.name.split('.').pop();   

        if(fileExtension != 'kml' && fileExtension !='kmz' && fileExtension != 'csv'){
            alert('Unsupported file type ' + f.type + '(' + fileExtension + ')');
            return;
        }

        functionfileLoaded() {
            loadCount++;
            //Check if we've loaded all the filesif (loadCount == files.length) {
                loadend(fileReaders);
            }
        }

        var fileReaderkmlcsv = newFileReader();                        
        fileReaderkmlcsv.onloadend = fileLoaded;
        fileReaderkmlcsv.onerror = function(event) {
            alert("ERROR: " + event.target.error.code);
        };          
        fileReaderkmlcsv.readAsText(f);
        fileReaders.push(fileReaderkmlcsv);
    }
  }

functionloadend(files) {
    //files now contains an array of completed FileReader objects
}

Note that I don't have direct experience of the FileReader object itself - if onloadend doesn't fire if an error occurs, you'll need to put similar logic in the onerror event as well to make sure that the loadCount variable still gets incremented/checked etc.

Post a Comment for "Asynchronous Execution In Javascript Any Solution To Control Execution?"