process.nextTick的常用方法
我应该多久使用一次process.nextTick
?
我理解它的目的(主要是因为这个和这个 )。
根据经验,当我必须调用callback时,我总是使用它。 这是一般的方法,还是有更多的呢?
另外,在这里 :
API对于100%同步或100%asynchronous非常重要。
100%同步意味着永远不要使用process.nextTick
和100%的asynchronous使用它?
考虑以下:
// 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。
这是一个有点人为的例子 – 显然, 在我们进行asynchronous调用之后,对i
进行分配有点愚蠢 – 但是在调用代码的其余部分可以完成之前调用callback代码的真实场景可能会导致微妙的错误。
因此,build议在否则同时调用callback时使用nextTick
。 基本上,任何时候你调用用户callback函数被调用的同一个堆栈中(换句话说,如果你在你自己的callback函数之外调用用户callback),使用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`. }); };