簡體   English   中英

process.nextTick的常用方法

[英]Common approach to process.nextTick

我應該多久或何時使用一次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`.
    });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM