Asynchronous execution in javascript any solution

2019-09-01 01:47发布

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
}

1条回答
甜甜的少女心
2楼-- · 2019-09-01 02:49

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:

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.

查看更多
登录 后发表回答