1

我尝试获取异步递归的函数。在 JS 中应该是这样的:

(function asyncRecursion(){
  doStuff();

  setTimeout(asyncRecursion, 1000);
})();

这是我在 CoffeeScript 中尝试过的:

(asyncRecursion = ->
  doStuff()

  setTimeout asyncRecursion, 1000
)()

但这被编译为:

(asyncRecursion = function(){
  doStuff();

  setTimeout(asyncRecursion, 1000);
})();

我在 JSHint 中遇到了一个名为“错误调用”的错误。对于第 1 行,asyncRecursion 函数。那么我怎样才能获得一个 JSHint 安全的异步递归函数。编译后的版本有效,但仍然存在 JSHint 错误。或者我应该忽略那个“错误的调用”。错误?

4

2 回答 2

0

I think JSHint is confused. An assignment is an expression and the value of that expression is the assignment's right hand side; that means that f = function() { ... } is an expression whose value is a function so (f = function() {...})() is perfectly valid JavaScript.

If you ask JSHint about this:

var f;
(f = 11)();

you'll get the same "Bad invocation" error and we see that JSHint probably isn't inferring the type of f, it just doesn't want to you (f = x)() for any x (even when x is definitely a function). I'd tell JSHint to go pound sand and find a better tool. However, if you must use JSHint, you can write your CoffeeScript in two pieces:

asyncRecursion = ->
  doStuff()
  setTimeout asyncRecursion, 1000
asyncRecursion()

and get this JavaScript:

var asyncRecursion;
asyncRecursion = function() {
  doStuff();
  return setTimeout(asyncRecursion, 1000);
};
asyncRecursion();

which JSHint is happy with. Both your original and the "make JSHint happy" version produce the same result when executed.

For extra fun with JSHint's lack of type inference, ask it what it thinks of this:

var asyncRecursion;
asyncRecursion = 11;
asyncRecursion();
于 2012-07-29T03:40:56.547 回答
0

你可以这样写:

asyncRecursion = do ->
  doStuff()

  setTimeout asyncRecursion, 1000

它将被编译成:

var asyncRecursion;

asyncRecursion = (function() {
  doStuff();
  return setTimeout(asyncRecursion, 1000);
})();
于 2012-07-30T16:31:11.190 回答