Executing the below using node - 6.0.
function A(callback) {
console.log('A');
callback();
}
function B() {
console.log('B')
}
function C() {
console.log('C');
}
A(C);
B();
// Result is A,C,B i expected that A, B, C
But changing the above example to use process.nextTick() prints A, B, C
function A(callback) {
console.log('A');
process.nextTick(() => {
callback();
});
}
function B() {
console.log('B')
}
function C() {
console.log('C');
}
A(C);
B();
Is this what we call as zalgo
? Can anyone provide me a realtime example of this, which will cause major breakdown ?
No, neither of these is zalgo. Your first
A
function always calls its callback synchronously, and should be documented as such. Your secondA
function always calls its callback asynchronously, and should be documented as such. Nothing is wrong with that, we use thousands of these every day. The outputsA C B
andA B C
are deterministic.Zalgo refers to the uncertainty whether a callback is asynchronous or not.
The output of the invocation
A(C); B();
would be totally unpredictable.First let me explain how the code works - see the comments in the code that I added:
This is exactly the same as it would be in any language like Java, C etc.
Now, the second example:
Update
Thanks to Bergi for explaining what is Zalgo in his answer. Now I better understand your concerns.
I've seen a lot of code like this:
Now, the callback can be either run immediately before
x()
returns if there are bad arguments, or after thex()
returns otherwise. This code is very common. For testing the arguments one could argue that it should throw an exception but let's ignore that for a moment, there may be some better examples of operational errors that are known immediately - this is just a simple example.Now, if it was written like this:
it would be guaranteed that the callback will never be invoked before
x()
returns.Now, if that can cause a "major breakdown" depends entirely on how it is used. If you run something like this:
then it will sometimes crash with the version of
x()
withoutprocess.nextTick
and will never crash with the version ofx()
withprocess.nextTick()
.