码迷,mamicode.com
首页 > Web开发 > 详细

Node.js 使用process.nextTick

时间:2014-08-25 02:16:33      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   io   strong   for   ar   

今天发现Node.js文档很好地解释了如何使用process.nextTick.

Node.js文档链接 http://nodejs.org/api/process.html#process_process_nexttick_callback

 

process.nextTick(function callback(){

});

Node.js确保callback会在处理下一个事件前被调用.

 

下面是Node.js文档的翻译: 

 

process.nextTick(callback)

在下一个事件循环中调用callback. 这个函数不是简单地等同与setTimeout(fn, 0), 它的效率更高. 一般来说它在所有其他I/O事件触发前被调用, 但是也有例外. 参考下面的process.maxTickDepth.

process.nextTick(function() {
  console.log(‘nextTick callback‘);
});

这个函数很重要, 尤其当你在开发一些API, 而这些API需要在一个对象被创建以后, 但是在所有其他I/O之前, 允许用户添加事件处理函数到这个对象.

function MyThing(options) {
  this.setupOptions(options);

  process.nextTick(function() {
    this.startDoingStuff();
  }.bind(this));
}

var thing = new MyThing();
thing.getReadyForStuff();

// thing.startDoingStuff() gets called now, not before.

非常重要, API应该100%同步, 或者100%异步. 考虑下面的例子: 

 

// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
function maybeSync(arg, cb) {
  if (arg) {
    cb();
    return;
  }

  fs.stat(‘file‘, cb);
}

这个API很危险, 如果这么调用API:

maybeSync(true, function() {
  foo();
});
bar();

这段代码不明确的地方是, 我们不清楚foo()和bar()哪个会被先调用.

这样写更好

function definitelyAsync(arg, cb) {
  if (arg) {
    process.nextTick(cb);
    return;
  }

  fs.stat(‘file‘, cb);
}

 

Node.js 使用process.nextTick

标签:style   blog   http   color   使用   io   strong   for   ar   

原文地址:http://www.cnblogs.com/tguitar/p/3933984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!