更新:如何使用自定义的大火事件JavaScript(不是异步)返回承诺的结果?

发布于 2025-01-18 09:52:50 字数 3250 浏览 2 评论 0原文

最终的?更新:解决方案 1:我将 func1 更改为不将值返回到我的 javascript 事件,而是使用

return DotNet.invokeMethodAsync('AppWASM', 'SetImageData', result);   

func1 将值直接返回到我的调用方法(因此我还更改了 func1(file) 的调用以不分配给变量)。然而,该方法必须是静态的这一限制让我陷入了原地踏步。我本可以使用它将其直接保存到我的数据库中,但从应用程序的角度来看,这不是一个好的解决方案。

将值保存到本地存储

 localStorage.setItem("thisimage", result); 

最终解决方案:我通过以下修改后的代码 。对于这个应用程序来说,这是最有意义的,因为这个想法是保存图像以查看用户是否想要保存它(或不保存)。所以我认为我通过走不同的路线来解决 Promise 的困惑 - 这就是我在类似问题中发现的。代码(和下图)显示了本地存储中存储的值。 =================================================== ===============** 第一次更新:我修改了代码,将 Promise eventArg 作为 JsonDocument 返回(属性设置为公共对象 Promise {get; set;} 在我的 eventargs 类中)。如何在 C# 中从 Promise 中提取数据?返回的 json 文档没有 Promise.result 元素。

我知道有类似的问题 - 脚本可以将 Promise 的结果记录到控制台,但返回的结果是未定义的 - 但答案是从异步函数调用 Promise 函数(许多答案都有注释,但它们没有工作)。由于我的“调用”脚本是针对一个事件的,因此我不知道如何使其异步。因此事件执行将继续,而不等待结果。我尝试分配给具有相同结果的顶级变量。自定义事件由浏览器事件触发,参数返回到 razor 页面中的方法。我想发送 imageB64string (或 globalimagevar)作为返回参数。这适用于 Net6 Blazor WASM(以及运行后的服务器)应用程序。

async function func1(fileParam) {
    await blobToBase64(fileParam).then(result => {
        localStorage.setItem("thisimage", result);
        return;
    });
}

async function blobToBase64(blob) {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return await 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 promise = "";
        
        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);

            func1(file);
        }
        return { isMultimedia, data };
     }
})

输入图片此处描述承诺结果为 json(部分显示):

在此处输入图像描述

原始结果/执行在承诺得到解决之前继续: imageB64string 是: function toString() { [native code] }

ImagePasteEvent.js:40 globalimagevar 是:

ImagePasteEvent.js:5 从 func1 记录:数据:图像/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVEAAAHaCAYAAAC5AXpZAAAgAElEQVR4nO3df3xU9YHv/xfJYZiEiTNhJmbCBJliiMFg DBo2CroGBbGyUlqxtqDfsqU+9F573W6rbRd7v9r7uHXd1nZdv2VXH1y37u1qa6tbyi60FCpxKWiWKJESDRBoEEISMyETMwzDMAnfP2byexICn0B....

注意:pastemultimedia 事件的基本代码归功于 费利佩·加维兰博客

Final? Update: Solution 1: I changed func1 to NOT return a value back to my javascript event, but instead to return the value directly to my calling method using

return DotNet.invokeMethodAsync('AppWASM', 'SetImageData', result);   

from func1 (so I also changed invoke of func1(file) to not assign to a variable). However, the limitation that the method had to be static had me going in circles. I could have used this to save it directly to my database but from the app's standpoint that wasn't a good solution.

Final Solution: I saved the value to local storage via

 localStorage.setItem("thisimage", result); 

which is in my revised code, below. For this app, that makes the most sense since the idea is to hold the image to see if the user wants to save it (or not). So I think I kind of got around the Promise confusion by just going a different route - which is what I found in the similar questions. The code (and image below) shows the value stored in localstorage.
=================================================================**
1st Update: I revised my code to return the Promise eventArg as a JsonDocument (property set as public object Promise {get; set;} in my eventargs class). How do I extract the data from this Promise in C#? The json document returned does not have a Promise.result element.

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.

async function func1(fileParam) {
    await blobToBase64(fileParam).then(result => {
        localStorage.setItem("thisimage", result);
        return;
    });
}

async function blobToBase64(blob) {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return await 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 promise = "";
        
        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);

            func1(file);
        }
        return { isMultimedia, data };
     }
})

enter image description herePromise result as json (partial shown):

enter image description here

Oriignal Result / execution continued before promise was resolved:
imageB64string is: function toString() { [native code] }

ImagePasteEvent.js:40 globalimagevar is:

ImagePasteEvent.js:5 logged from func1: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVEAAAHaCAYAAAC5AXpZAAAgAElEQVR4nO3df3xU9YHv/xfJYZiEiTNhJmbCBJliiMFgDBo2CroGBbGyUlqxtqDfsqU+9F573W6rbRd7v9r7uHXd1nZdv2VXH1y37u1qa6tbyi60FCpxKWiWKJESDRBoEEISMyETMwzDMAnfP2byexICn0B....

Note: Credit for the base code for the pastemultimedia event to Felipe Gavilan blog

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文