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();?
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.
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