简体   繁体   中英

Promise function with FileReader resolves prematurely

I'm opening a file to read contents like so:

convertBlobToBase64(blob){
    var convertPromise = new Promise(function(resolve, reject){
      var fileReader = new FileReader();
      fileReader.onload = function() {
          var dataUrl = this.result;
          var base64 = dataUrl.split(',')[1];
          resolve(base64);
      };

      fileReader.readAsDataURL(blob);
    });

    return convertPromise;
  }

I then call this function and pass the result data when it resolves:

myFunction(audioFile){
    var to64 = this.convertBlobToBase64(audioFile);
    to64.then(function(base64Val){
        var nextPromise = postCall();
        nextPromise.then(//stuff);
        return nextPromise;
    });

    return to64;
} 

However, when I call myFunction, it immediately returns a resolved promise that includes the converted data from convertBlobToBase64 , and not an unresolved promise that should be waiting on nextPromise as expected.

Instead, myFunction's .then is called immediately and fails as it doesn't have the correct data. Am I misunderstanding the Promise function?

Try this code:

myFunction(audioFile){
    var to64 = this.convertBlobToBase64(audioFile);
    return to64.then(function(base64Val){
        var nextPromise = postCall();
        return nextPromise.then(//stuff);
    });
} 

Btw you dont need to wrap another promise to a function. You can use your postCall as resolve func and chain it like this:

myFunction(audioFile){
  return convertBlobToBase64(audioFile)
    .then(base64Val => postCall())
    .then(//stuff)
} 

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