我应该多久或何时使用process.nextTick
?
根据经验,当我必须调用回调时,我总是使用它。这是一般方法还是还有更多?
另外,在这里:
API 要么 100% 同步,要么 100% 异步,这一点非常重要。
100% 同步仅仅意味着永远不使用process.nextTick
和 100% 异步总是使用它?
我应该多久或何时使用process.nextTick
?
根据经验,当我必须调用回调时,我总是使用它。这是一般方法还是还有更多?
另外,在这里:
API 要么 100% 同步,要么 100% 异步,这一点非常重要。
100% 同步仅仅意味着永远不使用process.nextTick
和 100% 异步总是使用它?
考虑以下:
// API:
function foo(bar, cb) {
if (bar) cb();
else {
process.nextTick(cb);
}
}
// User code:
function A(bar) {
var i;
foo(bar, function() {
console.log(i);
});
i = 1;
}
调用A(true)
打印未定义,同时调用A(false)
打印 1。
i
这是一个有点人为的例子——显然在我们进行异步调用之后分配给它有点傻——但在现实世界的场景中,在调用代码的其余部分完成之前调用回调代码可能会导致细微的错误。
因此,nextTick
当您以其他方式同步调用回调时使用的建议。基本上,只要您在调用函数的同一堆栈中调用用户回调(换句话说,如果您在自己的回调函数之外调用用户回调),请使用nextTick
.
这是一个更具体的例子:
// API
var cache;
exports.getData = function(cb) {
if (cache) process.nextTick(function() {
cb(null, cache); // Here we must use `nextTick` because calling `cb`
// directly would mean that the callback code would
// run BEFORE the rest of the caller's code runs.
});
else db.query(..., function(err, result) {
if (err) return cb(err);
cache = result;
cb(null, result); // Here it it safe to call `cb` directly because
// the db query itself is async; there's no need
// to use `nextTick`.
});
};