coding_hero
coding_hero

Reputation: 1769

Is it ever appropriate to use a 'return {value}' in node?

I've written a couple of express apps in Node, and I have a shameful gap in my knowledge. Please, go easy on me.

Is it ever appropriate to use this traditional format for functions in Node.js?

function isGreaterThanZero ( val ){
    return val > 0; 
}

or should you always use a callback?

function isGreaterThanZero (val, cb){
    if (val > 0) {cb(true);}
    else {cb(false);}
}

The async nature of Node.js has my brain turned inside-out, and I'm questioning everything.

Upvotes: 0

Views: 38

Answers (1)

maček
maček

Reputation: 77816

Of course it's appropriate

This is for synchronous code

function isGreaterThanZero(val){
    return val > 0; 
}

In lay terms, you'll use synchronous functions when there's nothing to wait for. You'll use synchronous functions outside of the exceptional cases noted below

For in-memory operations, things like basic calculations, string manipulations, array append, etc, you can use synchronous functions.

However, some synchronous functions do use callbacks but they're more for mapping or filtering purposes. In the comments, I see you asked about arr.filter. Other functions like arr.forEach, arr.map, or arr.reduce take callbacks but they're not implicitly asynchronous. In this case, the callback function is just used to augment the behavior of the called function.


This is for asynchronous code

function isGreaterThanZeroAsync(val, cb){
  // some long process...
  cb(val > 0);
}

You'll use asynchronous functions when you have something to wait for. Generally that's network, file system, or database access. An async function will allow you function to return (exit) immediately (as sync functions do) but the callback will get the value as soon as it's ready.

Here's a little async demo

function demoAsync(cb) {
  console.log("demo start");
  setTimeout(function() {
    cb("hello world");
  }, 1000);
}

console.log("init");
demoAsync(function(val) {
  console.log(val);
  console.log("demo done");
});
console.log("init done");

Output

init
demo start
init done
// 1000 ms later...
hello world
demo done

Why is this important?

You get "init", "demo start", and "init done" immediately. This demonstrates your program can continue while we're waiting for the demo to finish.

After 1000 ms we see "hello world" and "demo done".

Hooray! Everything happens in order.

Upvotes: 4

Related Questions