I am aware somewhat similar questions have been asked a gazillon times, but I really need to make an async call truly synchronous. I generally have to use AMD in an async fashion and I have to make sure some calls to require
execute synchronously - after the passed in callback has executed. It would be enough to make it work on chrome. Seems the trick can be done with ES6 yield
/await
. Unfortunately, yield
seems to require traceur
with chrome. In fact, I would like to have a lightweight, bare minimum solution and avoid introducing a big library footprint.
What's the bare minimum solution to get this implemented?
You can't do it. JavaScript in the browser is single-threaded and asynchronous. Do you really want your JavaScript blocking your UI thread as you wait for a file to load from the server?
I've never seen a situation where you need synchronous code in JS. Can you give us an example of why you feel like synchronous code is necessary?
As far as yield
/await
, you can make your code look like it is synchronous, but it is really a "coroutine" which means that the function has multiple entry points. In other words, it is still asynchronous. ES6 is getting generators and the yield
keyword, but await
is in the ES7 spec. Don't hold your breath for it.
You can use Traceur Babel or Regenerator to transpile your code to support generators and yield
, which is really nice. You can then use co to turn your generator function into a coroutine. I have an example of this working in chrome at LearnHarmony.
You can also use the import
/export
keywords in ES6 (using traceur or some other transpiler/polyfill) to get what looks like synchronous code: import Foo from 'foo'
. But don't let it fool you. It is also asynchronous. The Traceur compiler will transpile that code into async code.