nodejs: callback vs promise
Posted on December 23, 2014 • 2 minutes • 243 words
http://www.slideshare.net/wookieb/callbacks-promises-generators-asynchronous-javascript
The problem
Consider the code snippet below:
var x = doSomething();
typeof x === 'undefined'; // true
The second statement will not wait for the first one to complete, hence result in true
in the second statement.
When it comes to dealing with asynchronous in nodejs, we usually come down to 2 most popular options: callback and promise.
Callback
Callback is widely used but when we need 3 or more operations going in sequence, things are going to get ugly. Consider the following code snippet.
var doSomething = function(arg1, arg2, cb_fn) {
var sum = arg1 + arg2;
cb_fn(sum);
};
// usage
doSomething(10,20, console.log);
That is just one function with callback. Imagine this with 4 levels of callback. Welcome to CALLBACK HELL!!
var func_1 = function(cb) {
func_2(function(err, result) {
if (err) { cb(err); return; }
func_3(result, function(err, result) {
if (err) { cb(error); return; }
// WE NEED TO GO DEEPER
});
});
}
Promise
What is a promise ?
The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:
- pending - The initial state of a promise.
- fulfilled - The state of a promise representing a successful operation.
- rejected - The state of a promise representing a failed operation.
Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).
The most complete library for promise on Nodejs is Q
.