I am trying to improve my understanding of asynchronous JavaScript. To do this I have made a function that can take a long time to complete, which would completely block any other code from executing.
To test this, the function counts up. the first call counts from 1 to 10000000. The second call counts from 10 to 100.
CODE
async function LongTask(from, to) {
//Count up
let myNum = from
console.log(`counting from ${myNum} to ${to}`)
let start = new Date();
while (myNum != to) {
//console.log(`myNum: ${myNum}`);
await myNum++;
}
let end = new Date();
console.log(`counting from ${from} to ${to} done in ${end - start}ms!`);
}
//2 functions that take some time to finish
LongTask(1, 10000000);
LongTask(10, 100);
//Do unrelated stuff
console.log("Hello World!");
OUTPUT
counting from 1 to 10000000
counting from 10 to 100
Hello World!
counting from 10 to 100 done in 2ms!
counting from 1 to 10000000 done in 40389ms!
I managed to get it so that 10 to 100 will finish first due to it being faster. However, I get a warning on line 10 await myNum++;
saying 'await' has no effect on the type of this expression. Removing the await
keyword results in code blocking making it so that the 10 to 100 call of the function will have to wait for the much longer, unrelated 1 to 10000000 call to finish before being called.
Am I misunderstanding how asynchronous JavaScript works and is there a better way to ensure the 10 to 100 call finishes first?