Javascript Callback Hell

Javascript Callback Hell

Table of Contents

  • callback hell
  • Promise
  • bluebird


1 callback hell

Javascript callback hell looks like an inherent problem in js language, because of its asynchronous nature, writing callback functions and nesting them together looks the only way to coding for a newbie. 

 

It then gave programmers some mess code, if he persists to writing nesting callback code, and this mess codes are named as callback hell.

fs.readFile("file.json", function(err, val) {
    if( err ) {
        console.error("unable to read file");
    }
    else {
        try {
            val = JSON.parse(val);
            console.log(val.success);
        }
        catch( e ) {
            console.error("invalid json in file");
        }
    }
});

2 Promise

Promise is a new ES6(ECMAScript 2015) feature, is used for deferred and asynchronous computations. Promise is also a proposal, which represents the eventual result of an asynchronous operation. 

In a word, to solve the notorious callback hell puzzle.

var fs = require("fs");

function readFilePromise() {
    return new Promise(function(fulfill, reject) {
        fs.readFile("file.json", function(error, content) {
            if (error) reject(error);
            else fulfill(content);
        });
    });
}

readFilePromise().then(JSON.parse).then(function(val) {
    console.log(val.success);
})
.catch(SyntaxError, function(e) {
    console.error("invalid json in file");
})
.catch(function(e) {
    console.error("unable to read file");
});

3 bluebird

Bluebird is another popular and earlier implementation of the Promise proposal instead of the recent native ES6 support.

And it is still also the recommended one.

var Promise = require("bluebird");
var fs = require("fs");
Promise.promisifyAll(fs);

fs.readFileAsync("test.json").then(JSON.parse).then(function(val) {
    console.log(val.success);
}).catch(SyntaxError, function(e) {
    console.error("invalid json in file");
}).catch(function (e) {
    console.error("unable to read file");
});

So much elegant and human readable flat organized code now, is it?

Comments

Popular posts from this blog

Bluedroid stack in android

How to setup a NAT server?

Network programming in elisp