nodejs 中的 'console.time' 是同步的还是异步的

Is 'console.time' in nodejs synchronous or async?

本文关键字:异步 同步 console 中的 nodejs time      更新时间:2023-09-26

我正在尝试记录某些事情的时间。一般代码如下所示:

var stream = db.call.stream();
stream.on('data', function () {
    if (first) {
        console.time('doSomething');
    }
    stream.pause();
    doSomethingWithData(data);
    if (stopCondition) {
        console.timeEnd('doSomething');
        done();
    } else {
        stream.resume();
    }
});

我想知道对console.time的调用是阻塞还是异步?我在文档中找不到这个。

根据console.timeconsole.timeEnd的源代码,

Console.prototype.time = function(label) {
  this._times[label] = Date.now();
};

Console.prototype.timeEnd = function(label) {
  var time = this._times[label];
  if (!time) {
    throw new Error('No such label: ' + label);
  }
  var duration = Date.now() - time;
  this.log('%s: %dms', label, duration);
};

它们只是根据标签存储开始时间,并计算自标签计时以来经过的时间。

它们不会异步执行任何操作。

注意:在node.js中,如果函数是异步的,它将接受callback作为参数之一。