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
NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications. Asynchronous here refers to all those functions in JavaScript that are processed in the background without blocking any other request.
As a result, by applying parallel computing and asynchronous programming when dealing with independent tasks, you're able to perform these tasks way faster than with synchronous execution because they're executed at the same time.
Async/await helps you write synchronous-looking JavaScript code that works asynchronously. Await is in an async function to ensure that all promises that are returned in the function are synchronized. With async/await, there's no use of callbacks.
Sync is single-thread, so only one operation or program will run at a time. Async is non-blocking, which means it will send multiple requests to a server. Sync is blocking — it will only send the server one request at a time and will wait for that request to be answered by the server.
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; }
Nowadays this generator pattern can be a fantastic solution in many situations:
// nodejs script doing sequential prompts using async readline.question function var main = (function* () { // just import and initialize 'readline' in nodejs var r = require('readline') var rl = r.createInterface({input: process.stdin, output: process.stdout }) // magic here, the callback is the iterator.next var answerA = yield rl.question('do you want this? ', res=>main.next(res)) // and again, in a sync fashion var answerB = yield rl.question('are you sure? ', res=>main.next(res)) // readline boilerplate rl.close() console.log(answerA, answerB) })() // <-- executed: iterator created from generator main.next() // kick off the iterator, // runs until the first 'yield', including rightmost code // and waits until another main.next() happens
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With