简体   繁体   中英

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 solution?

function handleFileSelect(evt) {
    var files = evt.target.files;

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

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

        var fileReaderkmlcsv = new FileReader();                        
        fileReaderkmlcsv.onloadend = loadend;
        fileReaderkmlcsv.onerror = function(event) {
            alert("ERROR: " + event.target.error.code);
        };          
        fileReaderkmlcsv.readAsText(f);             
    } //- end for
} //handleFileSelect

function loadend(theFile) {
    alert("loadend");
    //code for processing my files
}

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

function handleFileSelect(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;
        }

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

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

function loadend(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM