I’m trying to understand how async functions work in JavaScript and how to write them, but it seems to me that the way the language handles async functions is pretty limited, but I can be wrong and, probably, I did not understand it.
I use Visual Studio Code (v. 1.66.2) and Chrome (v 100.0.4896.88) on Windows 10 X64.
Just for experimental purposes, I wrote a simple heavyLoad()
function that gets a delay parameter (that represents a millisecond value) and return true
after time elapsed:
function heavyLoad(delay) {
let startTime = (new Date()).getTime();
while(new Date().getTime() < startTime + delay);
return true;
}
If I write:
heavyLoad(5000);
console.log(“Hello”);
the console.log()
function is, obviously, executed after 5 secs, since I have to wait that heavyLoad()
function ends.
I’m trying to make heavyLoad()
function as asynchronous so that I can read, in the browser console, Hello immediately without waiting for heavyLoad()
function but I’m not able to do that: I’ve tried to create a promise object; I tried to use async
keyword but nothing works, since I have always to wait that heavyLoad()
function ends before reading Hello.
Is it possible to make heavyLoad()
function, essentially as it is, an async one as I meant?