process.nextTick的常用方法

Common approach to process.nextTick

本文关键字:方法 常用 nextTick process      更新时间:2023-09-26

我应该多久或何时使用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`.
    });
};