Using Promises with the Node API
Prerequisites
Objectives
By the end of this, developers should be able to:
- Explain the value of using promises instead of callback interfaces.
- Read Node documentation that uses callbacks and translate that into implementations using promises.
- Convert Node scripts using callbacks into scripts using promises.
Preparation
- Fork and clone this repository.
- Install dependencies with
npm install
.
Callbacks versus Promises
Callback drawbacks:
- Callbacks can be messy when they're nested: "callback hell". See
lib/copy-json.js
. - 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.
Pros for Promises:
- 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.
Lab: Research the Promises API
Take a few minutes to read the following API documentation for the native Promises.
Note function signatures and argument types as you read. What kind of object does a promise take when it is constructed?
Annotate-Along: Using Promises Instead of Callbacks
// remember that callback is something you write, in this case to perform some
// processing on parsed JSON
let readJSON = function (filename, callback){
fs.readFile(filename, 'utf8', function (err, res){
if (err) {
return callback(err); // what's going on here?
}
callback(null, JSON.parse(res)); // what if JSON.parse errors out?
});
};
What are some weaknesses in this code? And the following?
let readJSON = function (filename, callback){ // ๐ here
fs.readFile(filename, 'utf8', function (err, res){
if (err) {
return callback(err); // pass the error from readFile
}
try {
res = JSON.parse(res);
} catch (ex) {
return callback(ex); // pass the error from JSON.parse
}
callback(null, res); // don't pass the error, since we should have caught it
});
};
What about this instead?
let readJSON = function (filename) { // <-- look here
return new Promise((resolve, reject) => {
fs.readFile(filename, { encoding: 'utf8' }, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
}).then((res) => {
return JSON.parse(res)
});
};
readJSON('./example.jsom')
.then((pojo) => {
callback(pojo); // do something with the object
})
.catch((err) => { // handle error conditions
console.error(err);
});
That's too verbose. This is better:
let readJSON = function (filename) {
return new Promise((resolve, reject) => {
fs.readFile(filename, { encoding: 'utf8' }, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
})
.then(JSON.parse); // what can we surmise about .then?
readJSON('./example.jsom')
.then(callback) // do something with the object
.catch(console.error); // handle error conditions
copy-json.js
Code-Along: Promisify hey-yall.js
Lab: Pomisify randomizer.js
Lab: Promisify Additional Resources
- Promise - JavaScript | MDN
- Promises
- Promisees ยท Courtesy of ponyfoo.com
- wbinnssmith/awesome-promises: A curated list of useful resources for JavaScript Promises
- How to escape Promise Hell โ Medium
License
Source code distributed under the MIT license. Text and other assets copyright General Assembly, Inc., all rights reserved.