How can I make this work
var asyncToSync = syncFunc();
function syncFunc() {
var sync = true;
var data = null;
query(params, function(result){
data = result;
sync = false;
});
while(sync) {}
return data;
}
I tried to get sync function from async one, I need it to use FreeTds async query as sync one
You can do it with node-sync lib
Notice: your query must use standart callback call (with error first): callback(error, result). If you can't change query method, just create .async() wrapper (see github link).
Use deasync - a module written in C++ which exposes Node.js event loop to JavaScript. The module also exposes a
sleep
function that blocks subsequent code but doesn't block entire thread, nor incur busy wait. You can put thesleep
function in yourwhile
loop:Nowadays this generator pattern can be a fantastic solution in many situations:
The issue you are having is that your tight while loop is blocking. So I don't think your query callback will ever be run. I think you need to use setTimeout or the like to prevent the function from blocking, but should you do so, the function will return before the callback is called. This functionality must be implemented at a lower level.
If you are in the browser, you might check out this article. In node you have to rely on the implementation of whatever you're querying. It may or may not provide synchronous methods.
I've been using syncrhonize.js with great success. There's even a pending pull request (which works quite well) to support async functions which have multiple parameters. Far better and easier to use than node-sync imho. Added bonus that it has easy-to-understand and thorough documentation, whereas node-sync does not.