small medium large xlarge

Back to: All Forums  CoffeeScript
25 Jul 2011, 19:56
Aashay Desai (3 posts)

Pardon my confusion, but I was looking at the example in chapter 6.4, and I noticed that functions such as “assignToGame” and “handleMessage” use the “return” keyword.

If the idea is to write non-blocking async code, when is it safe to use “return” vs passing around callbacks? Does “return” function differently in CoffeeScript than it does in regular ol’ javascript?

25 Jul 2011, 23:19
Aashay Desai (3 posts)

To clarify a bit, I wanted to know when to use “return” vs the traditional callback-passing style that most Node apps use

26 Jul 2011, 00:01
Trevor Burnham (53 posts)

“return” has the exact same meaning in JavaScript as it does in CoffeeScript. While callback-passing is common in Node, in the interest of being non-blocking, it’s perfectly acceptable to have a function return a value if all the function does is use a modest amount of CPU and memory (no disk access, no Internet, no waiting for user input—in short, no I/O).

In the case of the functions you mentioned, there’s no need to use a callback for “assignToGame” and “handleMessage” because those functions are just performing simple operations on available data. In short, they’re synchronous. Callbacks are only needed for functions that can’t return their result until some external event occurs, such as a timer going off, a database server responding, or a file being read.

When it comes to execution order, CoffeeScript doesn’t do anything that ordinary JavaScript doesn’t do. So as long as you understand the JavaScript event model, you can rest assured that you understand it in CoffeeScript as well.

27 Jul 2011, 02:12
Aashay Desai (3 posts)

Thanks Trevor, that makes sense!

You must be logged in to comment