简体   繁体   English

Blazor JsInterop在每个promise解析后调用

[英]Blazor JsInterop Invoke after each promise resolves

Trying to get things working correctly in Blazor Server Side App. 尝试在Blazor Server Side App中正常运行。 I have an Uploader Component but it doesn't InvokeAsync after each promise is resolved on client side. 我有一个Uploader组件,但在客户端解析了每个promise之后它没有InvokeAsync。 It waits for all Images to load then Invokes the C# method. 它等待加载所有图像然后调用C#方法。 How would I get it to Invoke the C# method after each image is loaded? 如何在每个图像加载后调用C#方法?

I know JavaScript is single threaded but also tried with web workers and still does the same thing. 我知道JavaScript是单线程的,但也尝试过网络工作者,但仍然做同样的事情。

Sample repo can be found here https://dev.azure.com/twinnaz/BlazorUploader 样本回购可以在这里找到https://dev.azure.com/twinnaz/BlazorUploader

Gif of what's happening. 正在发生的事情的Gif。

https://imgur.com/a/aF4AQUf https://imgur.com/a/aF4AQUf

It should be able to invoke the C# method Async in parallel from javascript file if my thinking is correct. 如果我的想法是正确的,它应该能够从javascript文件并行调用C#方法Async。

This issue is related with Blazor and JS. 这个问题与Blazor和JS有关。 On JS you are not awaiting for GenerateImageData . 在JS上,你没有等待GenerateImageData

You should to use a modern for … of loop instead, in which await will work as expected: 你应该使用一个现代的for … of循环,其中await将按预期工作:

GetFileInputFiles = async (instance, fileInput) => {
    var files = Array.from(fileInput.files);
    for (const image of files) {
        var imagedata = await readUploadedFileAsText(image);
        console.log("sending");
        _ = await instance.invokeMethodAsync('GenerateImageData', imagedata);
        console.log("sent");
    };
};

On Blazor, I suggest to you to rewrite GenerateImageData as : 在Blazor上,我建议你重写GenerateImageData

    [JSInvokable]
    public async Task GenerateImageData(string data)
    {
        System.Console.WriteLine( "Receiving"  );
        ImageBase64.Add(data);
        await Task.Delay(1);
        StateHasChanged();
        System.Console.WriteLine( "Received"  );
    }

Result: 结果:

在此输入图像描述

GeneratePreviewImages = async (dotNet, fileInput) => { const files = Array.from(fileInput.files); const imageSrcs = files.map(file => getPreviewImageSrc(file)); loop(imageSrcs, dotNet); }; const loop = async (arr, dotNet) => { for await (const src of arr) { console.log(src); dotNet.invokeMethodAsync('GenerateImageData', src); } }; const getPreviewImageSrc = async (file) => { return URL.createObjectURL(file); };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM