When you declare a function normally:
readFile("~/Documents/todos.txt", "utf8", function (err, content) {
console.log("YOUR FILE CONTAINS:");
console.log(content);
});
readFile("~/Documents/todos.txt", "utf8", (err, content) => {
console.log("YOUR FILE CONTAINS:");
console.log(content);
});
Promise
: a commitment that sometime in the future, your code will get a value from some operation (like reading a file or getting JSON from a Website) or your code will get an error from that operation (like the file doesn’t exist or the Web site is down).
Pending
: Promise object has not resolved. Once it does, the state of the Promise object may transition to either the fulfilled or rejected state.Fulfilled
: Whatever operation the Promise represented succeeded and your success handler will get called. After fulfillment, the Promise:
Rejected
: Whatever operation the Promise represented failed and your error handler will get called. When it is rejected:
then
(successHandler, errorHandler)catch
(errorHandler)Success Handler
: function that has one parameter, the value that a fulfilled promise has.
Error Handler
: funvtion that has one parameter, the reason that the promise failed.
Handling Success with Then
readFilePromise("manifest.txt").then((manifest) => {
const fileList = manifest.split("\n");
console.log("Reading", fileList.length, "files");
});
readFilePromise("manifest.txt")
.then((manifest) => manifest.split("\n"))
.then((fileList) => fileList.length)
.then(
(numberOfFiles) => console.log("Reading", numberOfFiles, "files"),
(reason) => console.err("Badness happened", reason)
);
readFilePromise("manifest.txt")
.then((manifest) => manifest.split("\n"))
.then((fileList) => fileList.length)
.then((numberOfFiles) => console.log("Reading", numberOfFiles, "files"))
.catch((reason) => console.err("Badness happened", reason));
Using Promise.all
SUPER PROMISE
; it converts all non-promise values into Promise objects that are immediately in the fulfilled state.
Flattening Promises
readFilePromise("manifest.txt")
.then((manifestContent) => manifestContent.split("\n"))
.then((manifestList) => manifestList[0])
.then((fileName) => readFilePromise(fileName))
.then((otherFileContent) => console.log(otherFileContent));
// Interpreted as:
// 1. Read the file of the manifest.txt file and pass the
// content to the first then.
// 2. Split the content from manifest.txt on newline chars
// to get the full list of files.
// 3. Return just the first entry in the list of files.
// 4. RETURN A PROMISE THAT WILL READ THE FILE NAMED ON THE
// FIRST LINE OF THE manifest.txt! The next then method
// doesn't get called until this Promise object completes!
// 5. Get the content of the file just read and print it.