Using Promises with the Node API
Objectives
By the end of this, developers should be able to:
- Explain the advantages of using promises over callbacks.
- Read node documentation using callbacks.
- Rewrite node scripts using callbacks as scripts using promises.
Drawbacks to Callbacks
Asynchronous code necessitates callbacks. But dealing with lots of callbacks can be tricky:
- Callbacks can be messy when they're nested: "callback hell".
- Each callback will have to handle it's own errors if necessary.
- In complex programs, it will be hard to tell in what order callbacks fire.
Fortunately, there's a better way: Promises.
Lab: Research the Promises API
Promises are objects that represent steps in an asynchronous process. As of 2016, they are natively supported in Node.
Take a few minutes to read the API documentation on Promises. Note function signatures and argument types as you read. What arguments does a promise take when it is constructed?
Using a Promise
An instance of a Promise will reject and trigger catch or resolve and
trigger then.
new Promise((resolve, reject) => {
if (/* logic for if promise should reject or resolve */) {
reject(/* BOO return error */)
} else {
resolve(/* YAY return data */)
}
})
.then(/* success callback */)
.catch(/* failure callback */)Usually our Promise is defined within another function for clarity.
const returnsAPromise = function () {
return new Promise((resolve, reject) => {
if (/* logic for if promise should reject or resolve */) {
reject(/* BOO return error */)
} else {
resolve(/* YAY return data */)
}
})
}
returnsAPromise()
.then(/* success callback */)
.catch(/* failure callback */)Using Promises Instead of Callbacks
Promises offer several advantages over callbacks.
- Promises, like callbacks, make asynchronicity explicit.
- Promises, unlike callbacks, clarify the order of execution.
- Promises are easier to read than callbacks.
- Promises can simplify error handling.
const fs = require('fs')
// remember that callback is something you write, in this case to perform some
// processing on parsed JSON
const readJSON = function (filename, callback) {
fs.readFile(filename, 'utf8', (err, data) => {
if (err) {
return callback(err) // what's going on here?
}
callback(null, JSON.parse(data)) // what if JSON.parse errors out?
})
}
module.exports = readJSONWhat are some weaknesses in this code? And the following?
const fs = require('fs')
const readJSON = function (filename, callback) { // 👀 here
fs.readFile(filename, 'utf8', (err, data) => {
if (err) {
return callback(err) // pass the error from readFile
}
try {
data = JSON.parse(data)
} catch (error) {
return callback(error) // pass the error from JSON.parse
}
callback(null, data) // don't pass the error, since we should have caught it
})
}
module.exports = readJSONWhat about this instead?
const fs = require('fs')
const readJSON = function (filename) { // <-- look here
return new Promise((resolve, reject) => {
fs.readFile(filename, { encoding: 'utf8' }, (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
readJSON('./example.json')
.then((data) => {
return JSON.parse(data)
})
.then((pojo) => {
pojo = modifierFunc(pojo) // modify object
return pojo // explicitly returns pojo
})
.catch((err) => { // handle error conditions
console.error(err)
})That's too verbose. This is better:
const fs = require('fs')
const readJSON = function (filename) {
return new Promise((resolve, reject) => {
fs.readFile(filename, { encoding: 'utf8' }, (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
readJSON('./example.json')
.then(JSON.parse) // what can we surmise about .then?
.then(modifierFunc) // modify object --> returns what callback(prev) returns
.catch(console.error) // handle error conditionsRules for Promisifying Your Code
1. Only ever pass a function as a call back. NEVER pass a function invocation
Why?
The difference is `.then()` _expects_ a callback. If you invoke the function, the `.then` gets a _value_ NOT a function to invoke later.const json = "{'key': 'value'}"
getIndex()
.then(JSON.parse)
// vs
.then(JSON.parse(json))2. ALWAYS consider WHAT is being returned from each block of a promise chain
Be explicit if you need to
Why?
Because some methods don't return what you expect them to. If you're ever unsure, BE SURE by making it explicit!3. Safety third
Why?
'cause it should never be first or second.4. Indent once at the start, and then lineup your .thens and .catchs
Why?
Because formatting is important to humans.startingFunction()
.then(JSON.parse)
.catch(console.error)5. Never nest .thens--return out, and continue with the next .then in-line
startingFunction()
.then(JSON.parse)
.then((pojo) => {
functionThatReturnsAPromise(pojo)
.then(dontDoThis) // <-- creates promise hell!
})
.catch(console.error)Why?
Because nesting `.then`s defeats the purpose of promisesstartingFunction()
.then(JSON.parse)
.then((pojo) => {
// return the Promise to keep the chain going!
return functionThatReturnsAPromise(pojo)
})
.then(doThisInstead) // <-- narrowly avoids promise hell!
.catch(console.error)Additional Resources
- Promise - JavaScript | MDN
- Promises
- Promises and Async/Await
- Common Promise Mistakes
- wbinnssmith/awesome-promises: A curated list of useful resources for JavaScript Promises
- How to escape Promise Hell — Medium
License
- All content is licensed under a CCBYNCSA 4.0 license.
- All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact legal@ga.co.