0

Can anyone please help with the following?

In my main html page I use the onLoad method of the DOM like so:

<body onLoad="OnLoad()">

My OnLoad method is:

function OnLoad()
{
     var thing = new Thing();

     thing.GetAsync();

     alert("T");
}

Where Thing is:

function Thing()
{
}

Thing.prototype.GetAsync = async function ()
{
    var result = await this.AsyncFunc();

    alert(result);
}

Thing.prototype.AsyncFunc = async function ()
{
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("Text");
        }, 2000);
    });
}

When I run this I see "T" immediately and 2 seonds later I see "Text".

Is it possible to await the result of thing.GetAsync() so that "T" will always come after "Text" in the OnLoad method? I gather this may not be possible as it would be attmepting to pause the main browser thread?

user3738290
  • 445
  • 3
  • 16
  • 1
    The only change you need to make to fix this is to put `await` in front of `thing.GetAsync();` –  Jul 14 '20 at 14:33

2 Answers2

3

You need to define onLoad as an async function, and then await thing.GetAsync();

async function OnLoad()
{
     var thing = new Thing();

     await thing.GetAsync();

     alert("T");
}
Chris
  • 4,762
  • 3
  • 44
  • 79
  • Thanks for all the replies. I tried that. Unfortunately it doesn't work, the page stops loading. I thought to mark OnLoad method as async - function async OnLoad() - but just that in itself is enough to stop the the page from loading. So as even marking OnLoad as async didn't work, I tried TheMisir's method. Yes that gives me the alerts in the desired order, but I am trying to stop the remainder of the code in OnLoad form executing until "Text" has appeared. With this method the code below is still executing immediately – user3738290 Jul 14 '20 at 14:50
  • OK, got it. My fault. Thanks for all your help. I had "function async OnLoad()", should have had it as "async function OnLoad()" – user3738290 Jul 14 '20 at 14:59
1

You can add .then after async call to wait while Promise is completed. This will not block browser thread. Because the purpose of async calls is making experience smooth rather than blocking UI.

function OnLoad()
{
     var thing = new Thing();
     thing.GetAsync().then(function(result) {
         alert("T");
     });
}
TheMisir
  • 4,083
  • 1
  • 27
  • 37