0

I'm trying to understand some basic stuff about async function in JS.

I have this code:

start()

Start() is defined as follow:

async start(){
    my_function("function 1").then(() => {
        // Do something
    })

    my_function("function 2").then(() => {
        // Do something
    })
}

And then my_function(string) is defined as:

async my_function(string){
    let while_id = 1
    
    while(true){
        console.log("[" + string + "] " + while_id)
    } // while
}

So, being asynchronous functions I expect to see in the terminal a mix of strings belonging to function 1 and function 2. But in reality is printed only the while of function 1. Am I missing something?

Edit 1

You guys are telling me that while loop is not async. So what can be a solution in order to have the result I expect?

Steve
  • 406
  • 3
  • 11
  • 3
    Your `while` blocks the event loop. – sp00m Dec 16 '20 at 15:27
  • 3
    `while(true)` is not asynchronous – Darth Dec 16 '20 at 15:27
  • So while has been running as async/await function? Any solution using differents loops? – Steve Dec 16 '20 at 15:28
  • What are you actually trying to do? JS is single-threaded, so blocking code can be disastrous. Workers might help, but make sure you actually need them before jumping onto them. – sp00m Dec 16 '20 at 15:29
  • @sp00m I'm trying to do a mini-bot, that need to do, two stuff in parallel endlessly until certain condition is reach – Steve Dec 16 '20 at 15:32
  • 1
    If you use `await` somewhere in the loop, that will allow other things to run. – Barmar Dec 16 '20 at 15:36
  • You could also play with `setInterval`/`setTimeout` most probably, they can both be cancelled (when that certain condition is reached for instance). – sp00m Dec 16 '20 at 15:42
  • @kgangadhar This won't fix an endlessly blocking operation, JS is single-threaded. – sp00m Dec 16 '20 at 15:43
  • @sp00m, Got it, Thank you, so unless he takes care of the while, It will be a blocking call? `child_process` or `cluster module` is the solution? but how does that work within a function, I know how to use it on the entire application (cluster) – kgangadhar Dec 16 '20 at 15:51
  • @kgangadhar Put simply, JS runs "one synchronous code block at a time". So, if one of those synchronous code blocks takes ages to run (e.g. that `while (true)`), the other synchronous code blocks in the pipeline are just waiting for it to finish. – sp00m Dec 16 '20 at 15:53
  • @kgangadhar Well, just don't block :) I'm not super familiar with the `cluster` module to be honest, but as far as I know, it's used to run the same _app_ onto several cores, a kind of horizontal scaling _inside_ an instance (I could be very wrong though). Workers are there to help for code that _does_ need to be run "truly in parallel" (as explained in the question marked as duplicate), but use them only if really needed (which is quite rarely the case at the end). – sp00m Dec 16 '20 at 15:59

0 Answers0