Suppose I have an asynchronous function in Node.js, basically something like:
var addAsync = function (first, second, callback) { setTimeout(function () { callback(null, first + second); }, 1 * 1000); };
Now, of course, I can call this function in an asynchronous style:
addAsync(23, 42, function (err, result) { console.log(result);
I am wondering if you can somehow call this function synchronously. For this, I would like to have a sync wrapper function that basically does the following:
var sync = function (fn, params) { var res, finished = false; fn.call(null, params[0], params[1], function (err, result) { res = result; finished = true; }); while (!finished) {} return res; };
Then I could run addAsync synchronously by calling it like this:
var sum = sync(addAsync, [23, 42]);
Note. Of course, you will not work using params[0] and params[1] in reality, but use the arguments array accordingly, but I would like to make things simple in this example.
Now the problem is that the above code does not work. It simply blocks, because the while blocks and does not release the event loop.
My question is: is it possible to somehow launch this sample for its intended purpose?
I already experimented with setImmediate and process.nextTick and other things, but didn't help them. Basically, you had to tell Node.js to pause the current function, continue to run the event loop, and return to a later point in time.
I know that you can achieve something similar by using yield and generator functions, at least in Node.js 0.11.2 and higher. But I'm curious if this works even without?
Please note that I am fully aware of how to perform asynchronous programming in Node.js, the event loop and all related materials. I also fully understand that writing such code is a bad idea, especially in Node.js. And I am also fully aware that "active waiting" is also a stupid idea. Therefore, please do not give advice to find out how to do this asynchronously or something like that. I know it.
The reason I ask is simply out of curiosity and a desire to learn.