-
Notifications
You must be signed in to change notification settings - Fork 1
moj noms apvs 0222 asynchronous javascript
In JavaScript many of the calls made are asynchronous, as such we need mechanisms to handle the concurrent nature of the language and the implications it brings.
Due to the nature of asynchronous function calls a returned value cannot be guaranteed to have been received by the caller when it executes. Callbacks are functions passed as arguments to other functions which are then called after the called function completes. Callbacks are used to solve the problem by encapsulating the return value within itself which is then executed by the caller on completion of the asynchronous call.
- They are not intuitive.
- Harder to read than imperative code.
- Callbacks require us to nest dependent actions within the callback. This nesting leads to Callback Hell.
- Repetitive code that violates the DRY principle.
A Promise is a concurrency primitive that has at any time one of three states; pending, rejected, or resolved. The Promise represents the eventual result of some operation. All promise calls end with either a state of resolved or rejected. In practice Promise code works in a similar manner to throw and return statements and looks similar to synchronous input/output code.
Bluebird is a Promise library for Node.js. It is the most performant and full featured of the available libraries. It provides the following key features:
- Performance close to the use of plain callbacks.
- Can notify on the state of in-flight promises.
- Allows the cancelling of promises.
- Provides a utility to have callback returning libraries return promises.
Callback:
function doThing(callback) {
doThing2(function() {
doThing3(function() {
doThing4(function() {
doThing5(function() {
callback(result)
})
})
})
})
}
Promise:
function doThing() {
return doThing2()
.then(doThing3)
.then(doThing4)
.then(doThing5)
}
Many libraries have adopted the use of promises rather than callbacks. For those that haven't we can promisfiy them. That is, have Bluebird wrap the callbacks returned by the library as promises so we can treat them as if they implemented promise logic themselves.
In the following example the Bluebird library has been used to promisify the mongodb library and we have then made a call to our database which now returns a promise rather than a callback.
var Promise = require('bluebird')
var mongo = Promise.promisifyAll(require('mongodb'))
mongo.db.collection(collection).findOne({ _id: example })
.then(function (claimant) {
...
})
.catch(function (error) {
...
})