Thursday, February 16, 2017

How to cope with Callback Hell #1 Promise

We often fall into what is called "Callback Hell" when we write some asynchronous processes with Node.js, which is a problem the hierarchy of the code becomes too deep.

There are many  countermeasures and it looks a little messy, so I will sort out them in several posts. This time, I will introduce the way of returning Promise objects which hold the running state in an asynchronous process instead of making a callback an argument.

// An example of a function returning Promise.
var promiseFunction = function(message, timeout) {
    // Pass a function which has resolve and reject as arguments
    // when creating a Promise object.
    // * resolve: a function returning an object when the process succeeds
    // * reject: a function returning an error object when the process fails
    return new Promise(function(resolve, reject){
        setTimeout(function() {
            console.log(message);
            resolve(message);
            // Call reject function when an error occurs.
            // reject(error);
        }, timeout);
    });
};

// The usage of a Promise instance
var promise = promiseFunction('promise', 100);
// then: write post-processing
promise.then(function(result){
    console.log("result: " + JSON.stringify(result));
// catch: write error processing
}).catch(function(error){
    console.log("error: " + JSON.stringify(error));
});

Result

$ node promise.js
promise
result: "promise"

Reference

No comments:

Post a Comment