Promises and Q
promises?
A promise represents the result of an asynchronous operation
It exists in three states:
- Pending
- Fulfilled
- Rejected
So, it's similar to an event-listener...but
-
A promise can only succeed or fail once
-
If a promise has succeeded or failed and there is a callback, that callback will be called
THEN
"Promise me something then...."
Interaction with a promise takes place through its
then method, which registers those callbacks to handle the promise’s eventual value or the reason why the promise cannot be fulfilled.WHY USE PRomises?
To avoid the notorious callback hell
doSomething.method("user", "pass", {
success: function(user) {
query.find({
success: function(results) {
results.save({ key: value }, {
success: function(result) {
// the object was saved.
}
});
}
});
}
}); Error handling:
promises propagate errors,
promises propagate errors,
not calling any callback until an error handler is encountered
A basic promise with q
var promise = function(err, result) {
var deferred = Q.defer();
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve(result);
}
return deferred.promise;
};
So, the promise becomes an object that is thenable ...so do something with the result
promise.then(function(result) {
doSomething(result)
});
chaining
promise.then(function(result) {
return getSomething(result);
}).then(function(gotten) {
return doSomething(gotten);
}).fail(function(error) {
errorHandle(error);
}).done();
EXAMPLE
function statusCode(url) {
var deferred = Q.defer();
request.head(url, function(err, response, body) {
if (err) deferred.resolve(err);
deferred.resolve(response);
});
return deferred.promise
};
OR Similarly via Q.nfcall
function statusCode() {
return Q.nfcall(request.head, url)
};statusCode().then(function(data) {
console.log(data.statusCode) \\ returns 200
};Other libraries
Bluebird
RSVP
when.js
list goes on....
Promises Q
By ralucas
Promises Q
- 323