0

I would like to wrap an async FileReader tasks with a function that will allow me to wait until I have the file contents, then return the original "execute" function. This execute function needs to remain here for the activity to work.

I tried returning a promise on the wrapping function, but not sure how to use it to wait until FileReader's callback is done.

Can someone please point me in the right direction?

// @displayName DownloadFile
// @category Custom Activities
// @description This activity will initiate a file download given an HTML5 File object.
export class DownloadFile {

    //this method performs the download.
    async getBase64FromFile (file:File) : Promise<string> {
        var reader = new FileReader();
        reader.onload = function () {
          callback(reader.result);
          
        };
        reader.onerror = function (error) {
            callback("error");
        };
        reader.readAsDataURL(file);
    }     

    // Perform the execution logic of the activity.
    async execute(inputs: DownloadFileInputs): Promise<DownloadFileOutputs> {


        var base64file = this.getBase64FromFile(inputs.inputFile);
//I WANT TO WAIT HERE UNTIL base64file HAS A VALUE BEFORE CONTINUING.

        return { result: "File read successful: " + base64file  };
    }
}

Working UPDATE:

As @Bergi mentioned in his comment I used:

    private getBase64FromFile (file:File) : Promise<string> {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        return new Promise<string>(resolve => {
            reader.onload = function () {
              resolve(reader.result);
            };
        });
    }  

then used this to call:

var base64file = await this.getBase64FromFile(inputs.inputFile);
capdragon
  • 14,565
  • 24
  • 107
  • 153
  • Putting `async` in front of a function does not make it magically wait until some `callback` is called. You need to use the `Promise` constructor for this. – Bergi Jan 30 '18 at 16:21
  • 1
    Just use `var base64file = await this.getBase64FromFile(inputs.inputFile);` – Bergi Jan 30 '18 at 16:22
  • @Bergi see my update. That worked! I know i'm not supposed to say this, but thanks. – capdragon Jan 30 '18 at 16:54
  • 1
    Glad to have helped :-) I would recommend to put the `var reader = new FileReader(); reader.readAsDataURL(file);` inside the promise constructor - maybe they throw an exception, and this would lead to an automatic rejection. Also you must not forget `reader.onerror = reject`! – Bergi Jan 30 '18 at 17:25

0 Answers0