user840250 user840250 - 3 months ago 21
Node.js Question

Node.js async to sync

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

Answer

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 the sleep function in your while loop:

var asyncToSync = syncFunc();

function syncFunc() {
    var sync = true;
    var data = null;
    query(params, function(result){
        data = result;
        sync = false;
    });
    while(sync) {require('deasync').sleep(100);}
    return data;
}