我应该使用process.nextTick [英] Should I be using process.nextTick

查看:133
本文介绍了我应该使用process.nextTick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想围绕我的头时使用process.nextTick。下面我使用异步库来控制我的code流量,并想知道我是否应该在结束回调被调用nextTick与否。

  async.parallel([
    函数(回调){
        // 做一点事
        回调(数据);
    },
    函数(回调){
        // 做一点事
        回调(数据);
    }
]
// 回电话
功能(数据){
    process.nextTick(函数(){
        // 做一点事
    });
});


解决方案

不知道到底是什么你做某些事情是,我没有看到,你可能需要使用 nextTick <任何理由/ code>在这种情况下。您可以使用 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).

这篇关于我应该使用process.nextTick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆