1

我正在阅读Nodejs的教程,但我无法理解这段代码,请给我解释一下。

function async(arg, callback) {
  console.log('do something with \''+arg+'\', return 1 sec later');
  setTimeout(function() { callback(arg * 2); }, 1000);
}
function final() { console.log('Done', results); }

var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
var running = 0;
var limit = 2;

function launcher() {
  while(running < limit && items.length > 0) {
    var item = items.shift();
    async(item, function(result) {
      results.push(result);
      running--;
      if(items.length > 0) {
        launcher();
      } else if(running == 0) {
        final();
      }
    });
    running++;
  }
}

launcher();

此代码产生 run 2x 然后暂停一秒钟然后再次运行 2x 直到 items 数组中没有项目。

但是当我在 setTimeout 中删除匿名函数时:

setTimeout(callback(arg*2), 1000);

然后代码运行没有停止任何一秒钟。为什么?

4

2 回答 2

3

然后代码运行没有停止任何一秒钟。为什么?

因为不是将函数传递给,而是将函数调用setTimeout的返回值传递给它。

函数调用立即执行,然后setTimeout对返回值不做任何事情,因为它(可能)不是字符串或函数。

不要删除匿名函数包装器。

于 2012-08-30T08:17:45.757 回答
0

The reason the anonymous delegate is needed is because setTimeout expects an object of type function as it's first argument.

So you can either give it just a pre-defined function name directly:

function foo()
{
//do something
}

setTimeout(foo, 1000);

Or a delegate:

setTimeout(function(){/*dosomething*/}, 1000);

But this:

setTimeout(foo(param), 1000);

Is invalid because foo(param) isn't semantically correct in this context.

The alternative is to do something like:

setTimeout("foo(param);", 1000);

Because setTimeout will also accept a string of a function, but this is a bad idea because you lose the current scope and it's a pain to debug.

于 2012-08-30T08:14:26.717 回答