Notes

Promises

When you declare a function normally:

function loudLog(message) {
  console.log(message.toUpperCase());
}
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);
});

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

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.