0

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?

  • 4
    You can not make synchronous code like a loop just act like asynchronous code. So you need to use something that is asynchronous. That would be `setTimeout` https://developer.mozilla.org/en-US/docs/Web/API/setTimeout – epascarello Apr 18 '22 at 12:17
  • 2
    Functions are asynchronous because of the ways they interact with the runtime environment. For plain code as in your example, there's no way to say "please make the following block of code asynchronous". – Pointy Apr 18 '22 at 12:21
  • 2
    You can put your heavy load in a web worker. – Bergi Apr 18 '22 at 12:44
  • Have a look at [this](https://stackoverflow.com/q/39184297/4543207). The second snippet in the question answers your question but there is more. – Redu Apr 21 '22 at 19:18

4 Answers4

0

You can use WebWorker and Promise

Write your heavy load script in a separate file.

worker.js

onmessage = function(e) { 
    let startTime = (new Date()).getTime();
    while(new Date().getTime() < startTime + e.data);
    postMessage(true);
}

Run that webWorker in the main script file.

main.js

function heavyLoad(delay) {        
    return new Promise((resolve, reject) => {
        var myWorker = new Worker('worker.js');
        myWorker.postMessage(delay);
        myWorker.addEventListener('message', function(e) {
            // Log the workers message.
            resolve(e.data);
        }, { once: true });
    })
}

console.log("Starting")
console.time()
heavyLoad(5000).then(data=>{
    console.timeEnd()
})
console.log("end")

(Here I'm using console.time method to keep track of the execution time)

Pranavan
  • 1,287
  • 1
  • 6
  • 18
  • 1
    Don't forget to `myWorker.removeEventListener` (or use the [`once` option](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#parameters)), or this will leak memory – Bergi Apr 19 '22 at 12:55
  • @Bergi thanks. I've added that. – Pranavan Apr 19 '22 at 13:30
-1

For timeout there is setTimeout() method in javascript.

So you can simply use:

setTimeout(() => {
  console.log("Hello");
}, 5000);
kappe
  • 16
  • 1
  • 1
    The asker was more interested in how asynchronous functions work in Javascript, rather than just the usage of `setTimeout`. – Lajos Arpad Apr 18 '22 at 14:50
-1

Try following code to understand asynchronous working

function heavyLoad(delay) {        
        return new Promise((resolve, reject)=>{
         
            setTimeout(()=>{
                resolve(true)
            },delay)
        })
    }

    heavyLoad(5000).then(value=>{
        console.log(value)
    });
    console.log("Hello");

It will print hello first as you run the code and true after 5 seconds.

sodhankit
  • 1,138
  • 1
  • 14
  • 26
-1

You have to Use Settimeout function as you want to delay the function as long as you want and also setTimeout will act as asynchronous so you will log out hello immediately

function heavyLoad(delay) {        
    setTimeout(() => {
     return true
    },delay);
}

heavyLoad(5000);
console.log("hello");
Abbas Shaikh
  • 304
  • 1
  • 9