I know there are similar questions – scripts can log the result of a Promise to the console, but the returned result is undefined – but the answers are to call the promise function from an async function (and many answers have comments that they don’t work). Since my “calling” script is for an event, I don’t see how to make it async. So event execution continues without waiting for the result. I’ve tried assigning to a top level variable with same result. The custom event is fired by a browser event, and the args are returned to a method in the razor page. I’d like to send imageB64string (or globalimagevar) as a return arg. This is for Net6 Blazor WASM (and Server once it works) apps.
let globalimagevar = "";
async function func1(fileParam) {
await blobToBase64(fileParam).then(result => {
console.log("logged from func1: " + result);
console.log("result displays correcly in console");
globalimagevar = result;
return result;
});
}
function blobToBase64(blob) {
const reader = new FileReader();
reader.readAsDataURL(blob);
return new Promise((resolve, _ ) => {
reader.onloadend = () => {
resolve(reader.result);};});}
Blazor.registerCustomEventType("pastemultimedia", {
browserEventName: 'paste', createEventArgs: event => {
let isMultimedia = false;
let data = event.clipboardData.getData('text');
let imageB64string = "";
const items = event.clipboardData.items;
const acceptedMediaTypes = ["image/png"];
for (let i = 0; i < items.length; i++) {
const file = items[i].getAsFile();
if (!file) { continue; }
if (!items[i].type.includes('image')) { continue; }
if (acceptedMediaTypes.indexOf(items[i].type) === -1) { continue; }
isMultimedia = true;
const url = window.URL || window.webkitURL;
data = url.createObjectURL(file);
imageB64string = func1(file).toString;
console.log("imageB64string is: " + imageB64string);
console.log("globalimagevar is: " + globalimagevar);
}
return { isMultimedia, data, imageB64string };
}
})
Result:
imageB64string is: function toString() { [native code] }
ImagePasteEvent.js:40 globalimagevar is:
ImagePasteEvent.js:5 logged from func1: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVEAAAHaCAYAAAC5AXpZAAAgAElEQVR4nO3df3xU9YHv/xfJYZiEiTNhJmbCBJliiMFgDBo2CroGBbGyUlqxtqDfsqU+9F573W6rbRd7v9r7uHXd1nZdv2VXH1y37u1qa6tbyi60FCpxKWiWKJESDRBoEEISMyETMwzDMAnfP2byexICn0B….