Cleaning Nodejs/Express Code Smell

Ivy Lyu
3 min readOct 24, 2019

Hi there,

I did a code test about cleaning the Nodejs/Express code smell and I realized I did not fully understand how Nodejs/Express works and what are the newest writing styling used ES6/7 syntax. So here I want to do a quick review of what I have done and what I have learned from it.

Express for what?

Nodejs is only a runtime environment, just like Java and Python, to implement web HTTP requests, the Express framework needs to be used to do the CURD operations.

Features of Express?

Express, in short, is a series of middlewares calls. i.e. to GET something from API

localhost:3000/api/delivery/au?id=5

a middleware function looks like this:

app.get('/:id', function(res,req,next) {
const region = req.params.region;
const id = req.query.id; // get data from request URL
console.log("region:" + " " + region);
next(); //pass to the next middleware
}, function(res,req,next) {
res.json({
region:region,
id:id
});
} // send request data
);

For more middleware operations please see the Expressjs website.

Express VS. other frameworks (i.e. Koa)

Express is not the only framework for manipulating HTTP requests, Koa is also a framework to do that and I saw some articles said that compared to Express it is

  • more lightweight
  • can build robust applications
  • support more ES6/7 syntax

but I’ve never used that, so I just leave it there for future verification :)

Keep your Node app up with the times! (ES6/7)

Actually, I just start knowing Nodejs like half a year ago, so I’ve never used callbacks on the Node app, but there are callbacks on the code test, so I need to know how it works and then change them to promise.

Callback function VS Promise

Both of them are used for asynchronous programming

…Unfortunately, raw callbacks sacrifice the control flow, exception handling and function semantics we are familiar with in synchronous code. Promises provide a way to get those things back…

My understanding is: Promise gives the flexibility to use the async code somewhere else, you don’t need to pass them in a nested function, you can just reference a Promise object. Here is an example of using callback:

i.e. The following code snippet shows a callback is passed in the asyncExample function and the data variable is calculated and then is stored in the callback function for later use. In the useAsyncExample function, the data is used to add to the result array

function asyncExample (callback){
let data = 1;
data++;
callback(data);
}
...
function useAsyncExample (callback) {
let result = [];
asyncExample(function(data) {
result.push(data);
});
}

For me, using callbacks need a bit of logic here, since the callback does not have a name, so if the callbacks are passed in nested functions, I have to find the initial callback location and then organize the call logic, which is annoying!

If we use promise, things can be easier. Here is an example of promise:

function asyncExamplePromiseVersion () {
let data = 1;
// do sth with data
return new Promise((resolve, reject) => {
//error handling
if (data !== 5 ) {
reject();
}
else resolve(data);
}
async function useAsyncPromise () {
const result = asyncExamplePromiseVersion();
await result.then(data => console.log(data));
}

If we use a promise object, we don’t need to remember to pass the callbacks and we can also give out promise object a name(here we call it result), so I can remember what it is and represents for.

A promise can only have two possibilities (Resolve or Reject)once it finishes being processed. and the .then function unwraps what goes on in a promise (to see if the data has been processed as expect).

To sum up, the promise has advantages over callbacks

  • you can give promise a name (function semantics)
  • A promise naturally embedded error handling mechanism (Reject)
  • A promise doesn’t need to be nested(control flow)

const, let VS var

var is for global use, while let is within the function scope. const is for the purpose of immutability. If we discuss immutability advantages, it will be a long story, so I just stick to the conclusion: avoid var, use const and let.

To be Continue…

I also want to add error handling and Tests(Mocha/Chai) parts in the next articles, for now, that’s it!

--

--