Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - sync wait for async operation (sleep)

I know it was asked here many times and many times answered this is not a way how it should be done, but once more again :)

Is it possible, somehow, to call async function (such as timer / ajax call), basically common async task and synchronously wait until it ends without having 100%CPU usage and blocked browser?

Simple answer is enough - yes or no. If no i have to write all code depending on the async operation in "async way" Otherwise, it would be better ;)

imagine something like:

updateCSS("someurl.css")

function updateCSS(url) {

   var css = getCachedResource(url);

   css = css.replace(/regexp/gm, function(curUrl) {
     base64 = atob(getCachedResource(curUrl))
     return "data:image;base64," + base64
   })

}

function getCachedResource(url) {
  
  //...
  
  if (cached) {
    
    return cached
    
  } else {
    
    // doajax...    
    // watfor
    
    return loaded
  }
  
}

Of course, I can make it async, but the code will be.... terrible. Moreover, I have to make async all functions calling this function. Can you see simple solution? Blocking would be simplest I would say.

Thanks

like image 633
Fis Avatar asked Jan 25 '17 01:01

Fis


1 Answers

So just to summarize....

The answer is NO. It will never be possible to block the function or any other code and wait until the async operation is done. There is no mechanism for it supported directly by the JavaScript VM.

Especially in browser environment where it is not possible to manipulate the JavaScript virtual machine event loop (as it is possible with Node and how actually "deasync" library is doing it).

It is because of the JavaScript concurrency model and event processing as mentioned here:

https://developer.mozilla.org/cs/docs/Web/JavaScript/EventLoop

It has nothing to do with the fact the JavaScript is single threaded.

Also, please note, all stuff like Promises and new features like await/async are just a different way, how to write/manage the code for asynchronous tasks. It is not and never will be helpful in turning the async to sync.

So don't spend time, like me, by trying to find a way how to do it. Rather spend it by designing the async code ;)

like image 106
Fis Avatar answered Sep 23 '22 13:09

Fis