首先让我解释一下代码是如何工作的——看看我添加的代码中的 cmets:
// first you define function A and nothing happens:
function A(callback) {
console.log('A');
callback();
}
// then you define function B and nothing happens:
function B() {
console.log('B')
}
// then you define function C and nothing happens:
function C() {
console.log('C');
}
// now you call function A with argument C:
A(C);
// when A runs it prints 'A' and calls C before it returns
// now the C runs, prints C and returns - back to A
// A now has nothing more to do and returns
// Now the execution continues and B can be run:
B();
// B runs and prints 'B'
这与使用任何语言(如 Java、C 等)完全相同。
现在,第二个例子:
// first you define function A and nothing happens:
function A(callback) {
console.log('A');
process.nextTick(() => {
callback();
});
}
// then you define function B and nothing happens:
function B() {
console.log('B')
}
// then you define function C and nothing happens:
function C() {
console.log('C');
}
// Then you run A with C passed as an argument:
A(C);
// A prints 'A' and schedules running an anonymous function:
// () => { callback(); }
// on the next tick of the event loop, before I/O events are handled
// but after the current code stack is unrolled
// then it returns
// And then B is run:
B();
// B prints 'B' and returns
// Now nothing else is left to do so the next tick of the event loop starts
// There's one function to run, scheduled earlier so it runs.
// This function runs the `callback()` which was `C`
// so C starts, prints 'C' and returns
// The anonymous function has nothing else to do and returns
// There is no more things on the event loop so the program exits
更新
感谢 Bergi 在他的回答中解释了 Zalgo 是什么。现在我更好地理解了您的担忧。
这就是我们所说的 zalgo 吗?谁能给我一个实时的例子,这会导致严重的故障吗?
我见过很多这样的代码:
function x(argument, callback) {
if (!argument) {
return callback(new Error('Bad argument'));
}
runSomeAsyncFunction(argument, (error, result) => {
if (error) {
return callback(new Error('Error in async function'));
}
callback({data: result});
});
}
现在,如果有错误参数,回调可以在 x() 返回之前立即运行,否则在 x() 返回之后运行。这段代码很常见。为了测试参数,人们可能会争辩说它应该抛出一个异常,但让我们暂时忽略这一点,可能有一些更好的立即知道的操作错误示例 - 这只是一个简单的示例。
现在,如果它是这样写的:
function x(argument, callback) {
if (!argument) {
return process.nextTick(callback, new Error('Bad argument'));
}
runSomeAsyncFunction(argument, (error, result) => {
if (error) {
return callback(new Error('Error in async function'));
}
callback({data: result});
});
}
将保证在x() 返回之前永远不会调用回调。
现在,这是否会导致“重大故障”完全取决于它的使用方式。如果你运行这样的东西:
let a;
x('arg', (err, result) => {
// assume that 'a' has a value
console.log(a.value);
});
// assign a value to 'a' here:
a = {value: 10};
那么它有时会在不带process.nextTick 的x() 版本中崩溃,而在带有process.nextTick() 的x() 版本中永远不会崩溃。