2

I am having trouble using a promise to wait for a function to end before returning a value. I have looked over this forum response several times but cannot work out how to get it to work.

Post > How do I return the response from an asynchronous call?

The closest I have gotten is this, which still is not working. I would really appreciate it if someone can correct my mistake.

From Blazor:

string thing = await js.InvokeAsync<string>("GetThing");

To JavaScript:

window.CreateFontThumnailArray = () =>
{
    var thing = "";

    let start = new Promise(function (resolve, reject) {
        someObject.GetThingWithCallback(function (blob) {
            thing = "some text";
            //I want this to finish before parent function completes,
            //  and "return thing;" is called.
            resolve();
        });
    });

    Promise.all([start]);

    return thing;
}

I understand a bit of what is in the above-mentioned post and have managed to make some test functions work but not when it's in the callback of a function. Likes the above example "GetThingWithCallback(function(){"HERE"})"

My only other option would be to make this a void call. And then handle the callback Blazor side. But if I do that, I can't handle the immediate actions followed after calling the JavaScript function. Which would be most ideal.

Any help greatly appreciated.

1 Answers1

0

I managed to work it out, in case anyone needs to do this as well..

I was close, I just had to change to an async function. And change Promise.all([start]); to await start;

window.CreateFontThumnailArray = async () =>
{
    var thing = "";

    let start = new Promise(function (resolve, reject) {
        someObject.GetThingWithCallback(function (blob) {
            thing = "some text";
            //I want this to finish before parent function completes,
            //  and "return thing;" is called.
            resolve();
        });
    });

    await start;

    return thing;
}