Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: async callback vs sync callback vs process.nextTick vs setTimeout [duplicate]

I started to develop in node.js just a while ago. Lately, I did some deep dive into the 'event loop' and async mechanism of node. But still I'm not fully understand the different between sync and async callbacks.

In this example from node.js API, I understand why is not clear which function will be called first.

maybeSync(true, () => {
  foo();
});
bar();

But, what if we had:

syncOrAsync(arg, () => {
 if (arg) {
   cb(arg);
   return;
 }
});

syncOrAsync(true, function(result) {
  console.log('result');
});

console.log('after result);

It's not clear to me why they are always execute in sync order, although I did a callback function which should execute by the event loop after the stack is empty ( console.log('after result') was finished ). Do I always need to add process.nextTick(cb); to get async? And what is the diffrent between process.nextTick and setTimeout();?

like image 337
wizard Avatar asked Aug 08 '26 03:08

wizard


1 Answers

Unless you have something that is actually async, like timers or external calls etc. the code will always be synchronous, as that's the default state of all javascript code.
Adding a callback doesn't make it asynchronous

Here's an example of asynchronous code

function syncOrAsync(sync, cb) {
    if (sync) {
        return cb();
    } else {
        setTimeout(cb, 100); // async, waits 0.1 seconds to call callback
    }
}

syncOrAsync(true, function(result) { // synchronous call
    console.log('result 1'); // happens first
});

syncOrAsync(false, function(result) { // asynchronous call
    console.log('result 2'); // happens last, as it's async
});


console.log('result 3');     // happens second

Using process.nextTick() doesn't really make the functions asynchronous, but it does do somewhat the same

function syncOrAsync() {
    console.log('result 1'); // this happens last
}

process.nextTick(syncOrAsync);

console.log('result 2'); // this happens first

This would defer the execution of syncOrAsync until the next pass around the event loop, so it would be in many ways the same as setTimeout(syncOrAsync), but the function still wouldn't be asynchronous, the callback would execute immediately, we've just delay the entire execution of the function.

like image 182
adeneo Avatar answered Aug 10 '26 15:08

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!