Recently, asynchronous programming becomes a hit as slow jobs can perform while not blocking other jobs to be done. However, sometimes we want something to be done in a synchronous way like getting a single value from a query (you know callbacks are clumsy). In order to solve the problem, turning asynchronous functions to synchronous can solve the problem.
To turn asynchronous functions to synchronous, we need to set up a loop checking the result, therefore cause blocking.
Here’s the code: (we use javascript here because it’s straightforward)
function somethingSync(args){ var ret; //the result-holding variable //doing something async here... somethingAsync(args,function(result){ ret = result; }); while(ret === undefined){} //wait for the result until it's available, cause the blocking return ret; }
You could try using something like: Syncronize
Solved a similar problem for me
This doesn’t work in Javascript or in any single-threaded environment: you will block the main thread in your loop, preventing the callback to execute.
Oh… That’s right! This skill only works in multi-threaded environment. Thanks for reminding me 🙁
How to make it a multi-threaded environment. Normally browsers run in a single thread ?