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);