1

I have an async function which contains an awaited method in it, and since async/await are non-blocking, the moment the thread hits await in my notifyCustomer() method, it exits the method and proceeds to do other synchronous tasks.

async function notifyCustomer() {
  console.log("in notifyy customer");
  const customer = await getCustomer(1);
  //rest of my method

}
notifyCustomer();


//multiple intensive for loops running to consume time

The problem is, these multiple synchronous loops after my notifyCustomer() method would take about 20 seconds to execute, which means that for the thread to return to my notifyCustomer() method, I would have to wait for all of those for loops to end. Is there a way to check after finishing each of the for loops if my awaited customer is done so I can finish the rest of my async function before returning to finishing with my for loops? So that I dont have to wait for all of my code to finish running before I can get back to notifyCustomer.

Mohamed Motaz
  • 391
  • 1
  • 4
  • 13
  • _"since async/await are non-blocking"_ I don't think this is true. async functions still block. It can delay the execution of a function – evolutionxbox Mar 22 '21 at 11:00
  • But isnt the main purpose of await to block the execution of the current method in order to not block the execution of my program? Or am I missing something? – Mohamed Motaz Mar 22 '21 at 11:05
  • Most async operations are done on a different thread, so the JS code is delayed until it is finished. If the operation is not on a different thread, it will block – evolutionxbox Mar 22 '21 at 11:06
  • Isnt JS single-threaded? And is there anyway to achieve what I am hoping to in my question? – Mohamed Motaz Mar 22 '21 at 11:09
  • 1
    Consider looking into [web workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)? – evolutionxbox Mar 22 '21 at 11:10
  • This makes much more sense to use and does indeed solve my dilemma, thank you. – Mohamed Motaz Mar 22 '21 at 11:24
  • 1
    You shoud be able to do what you're asking without the need for web workers, but if they do the job you want, awesome. Regarding the (very good) question "Isn't JS single-threaded?", the article [If Javascript Is Single Threaded, How Is It Asynchronous?](https://dev.to/steelvoltage/if-javascript-is-single-threaded-how-is-it-asynchronous-56gd) might help. -- And if you really want to dive deeper, the video [What is the event loop anyway](https://www.youtube.com/watch?v=8aGhZQkoFbQ) is great. – Cat Mar 22 '21 at 11:30
  • 1
    (Also, TIL: [asynchronous vs non-blocking](https://stackoverflow.com/questions/2625493/asynchronous-vs-non-blocking).) – Cat Mar 22 '21 at 11:31
  • @Cat, can you specify how I can do it without using web workers? – Mohamed Motaz Mar 22 '21 at 11:37

0 Answers0