我想用一个函数包装一个异步FileReader任务,这个函数允许我等到我有文件内容,然后返回原来的"执行"功能。此执行功能需要保留在此处才能使活动起作用。
我尝试在包装函数上返回一个promise,但不知道如何使用它来等待FileReader的回调完成。
有人可以指出我正确的方向吗?
// @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 };
}
}
&#13;
工作更新:
正如@Bergi在评论中提到的,我用过:
private getBase64FromFile (file:File) : Promise<string> {
var reader = new FileReader();
reader.readAsDataURL(file);
return new Promise<string>(resolve => {
reader.onload = function () {
resolve(reader.result);
};
});
}
&#13;
然后用它来打电话:
var base64file = await this.getBase64FromFile(inputs.inputFile);
&#13;