sync-node : a npm module which makes node synchronous without blocking the main thread

author-avatar
Paul Shan Thu Mar 10 2016
$ npm install sync-node

Though on those rising days of JavaScript there was a debate on whether asynchronous programming is good or bad, but eventually with the massive growth of JavaScript and it’s modules and the success of its frameworks, it’s kind of an established fact that asynchronous programming method has nothing bad in it. However, in many cases we see the need of synchronous tasks in JavaScript and we try to resolve them using promises etc. Today I’m gonna show you an easy way to make things synchronous, but before that let’s discuss the exact problem first.

The problem

If task A is asynchronous and task B is synchronous (or even asynchronous), than how to start executing task B only after task A is completed.

The solutions

Promise: Using promise is a nice way to handle async tasks. But what if you have 50 tasks to run one after another? May be same kind of a task, but running it 50 times with different parameters. Eg: You are scraping a hotel website for prices of next 90 days. Firing 90 requests in parallel may help the hotel website to detect and block you. So you need one request to be fired only if the previous one is complete.

Synchronous Thread: There are plugins available to make things completely synchronous. But the problem with that is, JavaScript is single threaded. So if you block the thread to wait for some response, it hangs the entire application.

sync-node

The node module sync-node provides you an easy and efficient way to make things synchronous without blocking the main thread. This plugin uses the exact same mechanism used in generator tutorial.

What is sync-node?

sync-node is an npm plugin using which you can create a special queue to run your JavaScript. You can push your functions one after another in the queue and they will be executed in the same order they were pushed. If you Push function A first and then function B, than the value returned by function A will be the first argument of function B.

To install sync-node, run the following command.

$ npm install sync-node

An example of using sync-node

var SN = require('sync-node');
var pn = SN.createQueue();

pn.pushJob(function(){
    var valueToBeReturned = "fox";
    return new Promise(function (resolve, reject) {
        setTimeout(function() {
            console.log("I am supposed to be first!! I will return "+ valueToBeReturned);
            resolve(valueToBeReturned);
        }, 5000);

    })
});

pn.pushJob(function(res){
    var secondValueTpReturn = "VoidCanvas";
    console.log("I should come second!! Previous job's response was "+res);
    return secondValueTpReturn;
});

pn.pushJob(function(res){
    return new Promise(function (resolve, reject) {
        setTimeout(function() {
            console.log("Yes, I am third!! Prev response was "+res);
            resolve();
        }, 1000);

    })
});


pn.pushJob(function(res){
    console.log("Oh no.. I'm last!!");
});

Using the function createQueue(), we are creating an empty queue. Whatever is pushed in the queue will be executed one by one. To push a job in that queue, you should use the function pushJob(). If the function you are pushing is asynchronous, than it must return a proper Promise object, else sync-node will not be able to detect and wait till the time it gets executed.

Node.jsAjax

Written By

Paul Shan

Collections

  • E

    ES6

  • R

    React JS

  • C

    CSS

    Cascading style sheets only

  • S

    SEO

    Search engine optimization

  • E

    ES7

  • C

    CMS

    wordpress, drupal, jumla, magento and more


Show All

Tags

vue-js
advanced js
youtube
Web development
vue css
social share buttons
real-life-example
react datetime picker
progra
Online
MathJax
jsfiddle
jquery chart library
instant search using vue
handlebars
event loop
Design
console.log
best practices
imorph

Show All