I am trying to read some file using the JSInterop
provided by Blazor
.The problem is that even if in .C#
i await the method , it seems it does not await
it.Thus i can not retrieve the result provided by js
.
C#
<input name="start" type="file" onchange="@(async(x)=>await OnChangeS(x))" />
@functions{
private const string S = "start";
public async Task OnChangeS(UIChangeEventArgs ev) {
var str = await JSRuntime.Current.InvokeAsync<string>("methods.readFile", S);
Console.WriteLine("From blazor data is:" + (string.IsNullOrEmpty(str) ? "empty" : str));
}
}
JS
window.methods = {
readFile: function (fileName) {
let reader = new FileReader();
var file = document.querySelector('input[type=file ][name=' + fileName + ']').files[0];
var data = null;
reader.onload = () => {
data = reader.result;
console.log("from load data is"+data);
};
reader.onloadend = () => { console.log("from loadend data is"+data);return data };
reader.readAsText(file);
}
}
OUTPUT:
Given a sample json
file : { "name":"adita","age":33}
this is my output order:
WASM: Blazor S:empty
Fread.js:11 from load data is: {
"name":"adita",
"age":33
}
Fread.js:14 from loadend data is: {
"name":"adita",
"age":33
}
So my question is why is the method not awaited by Blazor
?
async
having no idea what else to try.It does not return anything with or withoutasync
.onload
andonloadend
are fired after the linereadAsText
so if i return anything after that it won't return anything toBlazor
.I thought that it would somehow pipe the return ofonloadend
toBlazor
.TaskCompletionSource
in C#) (The link points out it's deprecated, but is more to the point, and you can figure out the modern syntax from the links there)