Javascript, spliced FileReader for large files with Promises, how?

后端 未结 1 1617
一生所求
一生所求 2021-01-28 07:46

I\'m trying to use FileReader to read several files sequentially using promises for that. The problem is that I need to divide the reading operations in several chunks to make t

相关标签:
1条回答
  • 2021-01-28 08:48

    Your upload() function does not always return a Promise. It does in the else condition, but the if condition doesn't. You have a return statement, but it's inside of a callback, so it won't be received by the caller of upload.

    Try changing that to this:

    function upload() {
      if (start < end) {
        return new Promise(function (resolve, reject) {
          var chunk = uploading_file.slice(start, temp_end);
          var reader = new FileReader();
          reader.readAsArrayBuffer(chunk);
          reader.onload = function(e) {
            if (e.target.readyState == 2) {
              content += new TextDecoder("utf-8").decode(e.target.result);
              start = temp_end;
              temp_end = start + BYTES_PER_CHUNK;
              if (temp_end > end) temp_end = end;
              resolve(upload());
            }
          }
        });
      } else {
        uploading_file = null;
        console.log(content); // it shows the content of the file
        return Promise.resolve(content);
      }
    }
    

    Now, upload always returns a Promise instead of undefined.

    0 讨论(0)
提交回复
热议问题