我在学习https://nodejs.org/api/process.html#process_process_nexttick_callback_arg ,我被困在一个点上。我在下面引用它:
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.
我不明白为什么不清楚 foo() 还是 bar() 会先被调用。因为 arg 为真并且 maybeSync 函数同步工作。因此,一切都同步工作,我认为 foo() 将在 bar() 之前被调用。为什么这种情况并非如此?
The following approach is much better:
function definitelyAsync(arg, cb) {
if (arg) {
process.nextTick(cb);
return;
}
fs.stat('file', cb);
}
最佳答案
执行不明确,因为 fs.stat()
是异步的并且最快在下一个 tick 时执行,这意味着 bar()
将始终在 foo 之前执行()
。
但是,通过引入 if (arg)
子句,其中 cb()
立即执行,那么 foo()
将在 bar()
- 这是同步的。
因此,maybeSync()
在执行前不知道 arg
是什么,就没有可预测性。
definitelyAsync()
通过在 if (arg)
分支中安排对 cb()
的调用,强制始终异步执行,这将始终导致 bar()
在 foo()
之前执行,而不管 arg
值如何。
关于javascript - API 应为 %100 同步或 %100 异步示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38158830/