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