Writing Synchronous Code in Node

First of all, you should be writing asynchronous code in node since that is the philosophy behind it.

But I’ve been experimenting with using node to write non-webapp, throwaway code and sometimes it helps to write synchronous code. This is how you’d do it.

There’s a synchronous library called synchronize.js.

Install it in your development environment

npm install synchronize

Then use it. Here’s a sample

var db = require('./db.js');
var sync = require('synchronize');

sync(db.connection, 'query');

function getDBValues() {
  var sql =
      'SELECT value'
    + ' FROM table'
  var values = [];
  var rows = db.connection.query(sql);
  for(var i=0; i < rows.length; i++) {
    values[i] = rows[i].value;
  return values;

sync.fiber(function() {
  var values = getDBValues();


I’ll point out the necessary pieces.

First is the import of synchronize

var sync = require('synchronize');

Then declare the object and the functions within that object which you want to be synchronous. Here, I declare my db.connection object’s query() method to be synchronous

sync(db.connection, 'query');

Wrap your code in a sync.fiber() method.

sync.fiber(function() { ...} )

Now you can make synchronous calls like this

  var rows = db.connection.query(sql);

instead of asynchronous code like

  db.connection.query(sql, function(err, rows) {
Tagged , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: