While i'm studying https://nodejs.org/api/process.html#process_process_nexttick_callback_arg , i'm stucked at a point. I'm quoting it below :
It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example:
// WARNING! DO NOT USE! BAD UNSAFE HAZARD!
function maybeSync(arg, cb) {
if (arg) {
cb();
return;
}
fs.stat('file', cb);
This API is hazardous because in the following case:
maybeSync(true, () => {
foo();
});
bar();
It is not clear whether foo() or bar() will be called first.
I didn't understand why it is not clear whether foo() or bar() will be called first. Because arg is true and maybeSync function works synchronously. Thus everything works synchronously and foo() will be called before bar(), i think. Why this is not true for this case?
The following approach is much better:
function definitelyAsync(arg, cb) {
if (arg) {
process.nextTick(cb);
return;
}
fs.stat('file', cb);
}