How to determine that all the files have been read and resolve a promise

前端 未结 2 382
南笙
南笙 2021-01-25 08:58

The following code is responsible for reading files. My requirement is how to find whether all files has been read so that I can return or resolve a promise from the parent fun

2条回答
  •  佛祖请我去吃肉
    2021-01-25 09:47

    What if I change the code structure to this

     $.when(readmultifiles(files)).then(
                            function(status) {
                                alert(status + ", things are going well");
                            },
                            function(status) {
                                alert(status + ", you fail this time");
                            },
                            function(status) {
                                $("body").append(status);
                            }
                    );
           function readmultifiles(files) {
    
                var dfrd = $.Deferred();
                // Read first file
                setup_reader(files, 0);
    
                function setup_reader(files, i) {
                    var file = files[i];
                    var name = file.name;
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        readerLoaded(e, files, i, name);
                    };
                    reader.readAsBinaryString(file);
                    // After reading, read the next file.
                }
    
                function readerLoaded(e, files, i, name) {
                    // get file content  
                    var bin = e.target.result;
                    // do sth with text
    
                    namee.push(name);
                    // If there's a file left to load
                    if (i < files.length - 1) {
                        // Load the next file
                        setup_reader(files, i + 1);
                    } else {
                        dfrd.resolve(namee.join(','));
                    }
                }
                return dfrd.promise();
          }
    

提交回复
热议问题