MVC and Async programming with Nodejs

Audrus
2 min readOct 31, 2017

--

Trakai Island Castle, Lithuania

In PHP I have worked with a MVC architectural pattern. I like this pattern because it is great structured. All PHP frameworks have the MVC pattern.

Now I work with a new project and there i use the Nodejs platform with Expressjs framework and a Handlebarsjs template system. Expressjs by default doesn’t have MVC pattern, but you can easy create MVC pattern. I hate functional programming, therefore I use classes (ES6) in the MVC.

My folders structure:

parent_folder
— app
— — controllers
— — — auth
— — models
— — views
— public // there Nginx gets files (js, img)
— config
— resources
— — assets
— — — js
— — — — // there is Reactjs
— — — stylus
— — locales
— — — en
— — — lt
-services

The MVC with Expressjs works perfectly, but I had problem with async programming and Handlebarsjs. The Handlebarsjs doesn’t support async programming.

For example: I have a header.hbs partial, and I want to share MySQL menu data to a header.hbs template. But these data come in asynchronous mode. The Handlebarsjs has helpers, but its work only in synchronous mode. Each page has a new controller.

Do I have to share menu data in each controller? But if I will have more data, each my controller will have a lot of duplicate data.

So, I created parrent controller.

I work with async/await function (ES8), and my code is like synchronous. The method configureHandlebar is async and it works with two async methods from other objects (assetsService and typeService).

The TypeService object has async method too.

In all children controllers I extend my parrent controller.

When we work with async/await we get always promises. We can’t get data outside with return:

const data = this.configureHandlebar(req, res) // wrong!

We have to create the promise:

this.configureHandlebar(req, res)
.then(context => {
// ....
})

Child controller can share specific data for the Handlebarsjs too.

context.loginMessage = (typeof loginMessage !== 'undefined') 
? loginMessage : ''

And now the Handlebarsjs gets all variables.

--

--