4

Is is possible to convert an asynchronous/callback based method in node to blocking/synchronous method?

I'm curious, more from a theoretical POV, than a "I have a problem to solve" POV.

I see how callback methods can be converted to values, via Q and the like, but calling Q.done() doesn't block execution.

Scott Weinstein
  • 18,890
  • 14
  • 78
  • 115

3 Answers3

2

The node-sync module can help you do that. But please be careful, this is not node.js way.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Vadim Baryshev
  • 25,689
  • 4
  • 56
  • 48
1

To turn asynchronous functions to synchronous in 'multi-threaded environment', we need to set up a loop checking the result, therefore cause blocking.

Here’s the example code in JS:

    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;
    }

OR

synchronize.js also helps.

Lakshmi Swetha G
  • 2,691
  • 1
  • 9
  • 13
  • 1
    This answer is incorrect: if `somethingAsync` does **not** call `function(result)` synchronously before it returns, then the `while` loop will occupy the JavaScript thread and prevent the callback function from being called - meaning `ret` stays `undefined`. – traktor Apr 02 '22 at 09:24
-1

While I would not recommend it, this can easy be done using some sort of busy wait. For instance:

var flag = false;
asyncFunction( function () { //This is a callback
    flag = true;
})

while (!flag) {}

The while loop will continuously loop until the callback has executed, thus blocking execution.

As you can imagine this would make your code very messy, so if you are going to do this (which I wouldn't recommend) you should make some sort of helper function to wrap your async function; similar to Underscore.js's Function functions, such as throttle. You can see exactly how these work by looking at the annotated source.

Nick Mitchinson
  • 5,452
  • 1
  • 25
  • 31