基于ts / js-library承诺

时间:2018-01-13 22:42:31

标签: javascript promise es6-promise

我已将this file reader实施到我的项目中。

我想在文件读取完成后返回一个承诺,但我不知道如何从那里传播承诺。

class MyClass {

  constructor() {}

  public start(file) {
    parseFile(file);
  }

  private parseFile(file) {
      let fileSize = file.size;
      let chunkSize = 10000;
      let offset = 0;
      let self = this;
      let readBlock = null;
      // How do I get this success function to return a promise to the user?
      let success = function() { return new Promise...? };

      let onLoadHandler = function(evt) {
          if (evt.target.error == null) {
              offset += evt.target.result.length;
              chunkReadCallback(evt.target.result);
          } else {
              chunkErrorCallback(evt.target.error);
              return;
          }
          if (offset >= fileSize) {
              success(file);
              return;
          }

          readBlock(offset, chunkSize, file);
      }

      readBlock = function(_offset, length, _file) {
          let r = new FileReader();
          let blob = _file.slice(_offset, length + _offset);
          r.onload = onLoadHandler;
          r.readAsText(blob);
      }

      readBlock(offset, chunkSize, file);
   }
}

今天它的工作原理如下:

let x = new MyClass();
x.start(file);

我希望它能像这样:

let x = new MyClass();
x.start(file).then(() => { console.log('done') });

我将返回Promise放在何处,以便用户可以处理承诺?

谢谢!

1 个答案:

答案 0 :(得分:0)

以下内容应将readFile转换为承诺:

private parseFile(file,chunkSize,offset) {
  let fileSize = file.size;
  let self = this;

  readBlock = function (_offset, length, _file) {
    return new Promise(
      function(resolve,reject){
        let r = new FileReader();
        let blob = _file.slice(_offset, length + _offset);
        //https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload
        r.onload = function(e){
          if(e.target.error!==null){
            reject(e.target.error);
          }
          else{
            resolve(e.target.result)
          }
        };
        //https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onerror
        r.onerror = function(err){
          reject(err);
        }
        r.readAsText(blob);    
      }
    )
  }

  return readBlock(offset, chunkSize, file);
}

您可以让调用者定义块大小以及何时读取下一个块。

如何使用此功能的示例:

x.parseFile(file,file.size,0)
.then(
  function(textData){
    console.log(textData);
  }
);

//read in chunks of 1000
function readInChunks(file,chunkSize=1000,offset=0,data=""){
  return x.parseFile(file,chunkSize,offset)
  .then(
    function(textData){
      if(offset+chunkSize>=file.size){
        return data+textData;
      }
      console.log("get next chunk");
      //recursively call itself
      return readInChunks(file,chunkSize,offset+chunkSize,data+textData);
    }
  )
}
//call read in chunks
readInChunks(file,/* optional, defaults to 1000 */500)
.then(
  function(textData){
    console.log("got data:",textData);
  }
) 
相关问题