且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该使用process.nextTick

更新时间:2023-11-10 18:23:40

不知道到底是什么你做某些事情是,我没有看到,你可能需要使用 nextTick 在这种情况下。您可以使用 nextTick 当你有理由推迟函数的执行事件循环的下一次迭代。你可能需要阅读理解 process.nextTick 了解更多详情。

另外请注意,异步的平行任务完成回调带参数的犯错,数据,所以你应该做的:

  async.parallel([
    函数(回调){
        // 做一点事
        回调(空,数据);
    },
    函数(回调){
        // 做一点事
        回调(空,数据);
    }
]
// 回电话
功能(ERR,数据){
    如果(ERR)抛出走错了路。
    // 做一点事
});

的主要区别在于最后调用回调函数立即如果并行任务之一返回错误(电话回调与truthy第一个参数)。

I'm trying to get my head around when to use process.nextTick. Below I'm using async library to control my code flow and was wondering if I should be calling nextTick in the end callback or not.

async.parallel([
    function (callback) {
        // do something
        callback(data);
    },
    function (callback) {
        // do something
        callback(data);        
    }
], 
// callback
function (data) {
    process.nextTick(function () {
        // do something
    });
});

Without knowing exactly what your 'do something' is, I don't see any reason that you'd need to use nextTick in this situation. You use nextTick when you have reason to defer execution of a function to the next iteration of the event loop. You might want to read Understanding process.nextTick for more detail.

Also, note that async's parallel task completion callbacks take arguments err, data, so you should be doing:

async.parallel([
    function (callback) {
        // do something
        callback(null, data);
    },
    function (callback) {
        // do something
        callback(null, data);        
    }
], 
// callback
function (err, data) {
    if (err) throw err;
    // do something
});

The major difference being that the final callback is invoked immediately if one of the parallel tasks returns an error (calls callback with a truthy first argument).