Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke JS async method from Blazor

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 ?

like image 603
Bercovici Adrian Avatar asked Dec 29 '25 05:12

Bercovici Adrian


1 Answers

I have solved it by wrapping my FileReader result in a Promise.I was not actually sending anything back as @Kirk Woll pointed out.

window.methods = {

    readFile: function (fileName) {
        let reader = new FileReader();
        return new Promise((resolve, reject) => {


            var file = document.querySelector('input[type=file ][name=' + fileName + ']').files[0];
            reader.onerror = () => { reader.abort(); reject("Error parsing file"); };
            reader.onload = () => {
                var data = reader.result;
                console.log("from load data is: " + data);
                resolve(data);


            };
            reader.readAsText(file);
        });
    }
}
like image 148
Bercovici Adrian Avatar answered Jan 01 '26 15:01

Bercovici Adrian