The proposed approaches don't scale well, especially if you need error handling: you will get spaghetti of lambdas in complex cases. So the examples above should be treated like an entry-level tutorial and shouldn't be used in production.
You can use return
to return values asynchronously, but you should return not a value but some kind of continuation. Futures and promises are one example of such continuations. Look for NPM libraries providing them. See q
and q-http
libraries for an example.
See also the following related questions:
What is the benefit of a 'promise' abstraction in CommonJS?
Understanding promises in node.js
I think q
library is distinguished because it has sister libraries (q-io
, q-http
) implementing most of the standard node.js library using promises.
In fact, an early standard library for node used promises, but later they decided to use callbacks. It was not because of promises was not good, but because callbacks are lower-level.