"git@gitlab.caltech.edu:cs24-19fa/git_rec_nano.git" did not exist on "26fe2118c42165f8390776899e62319d150d6cb2"
Commit 53fbefe6 authored by Caleb C. Sander's avatar Caleb C. Sander
Browse files

Initial commit

parents
Showing with 981 additions and 0 deletions
+981 -0
# CS 11 Asynchronous Programming track (SP 2020)
## Course description
TODO
## Me description
TODO
## JavaScript reference
There is a description of the important parts of the JavaScript language in [`notes/js/js.md`](notes/js/js.md).
It also has information specific to running JS in the browser and through Node.js.
You're welcome to read as much of it as you want, but it's quite long.
I will point out sections of it that may be useful on each assignment.
## Schedule
| Weeks | Topic and notes | Project | Due date |
| ----- |---------------- | ------- | -------- |
| 1-2 | [Callbacks](notes/callbacks/callbacks.md) | [Minesweeper](specs/minesweeper/minesweeper.md) | 2020-04-17 |
| 3 | [Promises](notes/promises/promises.md) | [`make`](specs/make/make.md) | 2020-04-24 |
| 4 | Streams | `grep` | 2020-05-01 |
| 5 | HTTP | Wiki Game | 2020-05-08 |
| 6 | WebSockets | Chat server | 2020-05-15 |
| 7 | | Chat client | 2020-05-22 |
| 8-9 | `async`-`await` | MiniVC | 2020-06-05 |
# Asynchronous idioms: event handlers and callbacks
## An example in the browser
JavaScript was designed as a programming language to run on webpages so that users can interact with the content on the page.
Some examples of things webpages often do in JavaScript:
- Show/hide part of the page when the user clicks on a button
- When the user enters some text in a form, check that it is a valid email address
- Update the state of a game when the user presses a key
- Upload data to a server
- Periodically request updated data from a server
[Here](click.html) is a simple example of JS code (between the `<script>` and `</script>` tags) that displays a message when the user clicks on a button:
```html
<html>
<body>
<button id='alert-button'>Click me!</button>
<script>
// We use the `id` property of the button to access it from JS
const button = document.getElementById('alert-button')
button.onclick = () => {
// You could put any other code you wanted here
// and it would run each time the button is clicked
alert('Button was clicked')
}
</script>
</body>
</html>
```
If you open this HTML file in the browser, it will show a button on the screen.
Each time the button is clicked, it displays a message saying that the button was clicked.
## How does this work?
Let's tease apart the code responsible for making button clicks display the message.
First, note that `() => alert('Button was clicked')` is a *function* in JS.
When this function is called, it causes the message `Button was clicked` to appear.
Then `button.onclick = ...` tells the browser "this is the function I want to attach to the click action on `button`.
When a user interacts with the webpage, the browser figures out whether the button was clicked, and if so, it runs the function stored in `button.onclick`.
## How doesn't this work?
Note that nowhere does our code say something like "wait until `button` is clicked" or "was `button` clicked yet?".
If you've dealt with user input in another language, you might have expected our JS code to handle button clicks to look more like:
```js
// 1.
while (true) {
button.waitForClick()
alert('Button was clicked')
}
// or
// 2.
while (true) {
if (button.wasClicked()) {
alert('Button was clicked')
}
}
```
So why doesn't JS use an interface like one of these?
1. We call a function `button.waitForClick()` that asks the browser to pause our code until the user clicks the button.
Although this could work in our simple example, what if the user might click either of two buttons and we want to respond to both?
If we call `button1.waitForClick()` and they click `button2` instead, we will fail to detect their click.
2. This approach solves the issue of not being able to respond to multiple events: we could just add an `if (button2.wasClicked())` inside the loop.
However, it has a more subtle problem.
The loop may run billions of times before the user actually clicks the button.
Since our program can't actually do anything until the user finally clicks the button, this is an incredible waste of the processor's time.
We see that the "event handler" approach used by JS has two main benefits: it can easily set up handlers for thousands of events at once, and no JS code runs while we wait for an event to occur.
## Combining asynchronous events in parallel
Imagine that we would like to wait until several events have all happened before running some code.
In [this example](lock1.html), we make a combination lock with 4 digits and want to take an action when all the digits are correct:
```js
// Adds a digit to the lock. When the digit changes,
// `changeCallback()` will be called with the new value.
function makeLockDigit(changeCallback) {
// ... (the full code is at the link above)
digit.onchange = () => changeCallback(Number(digit.value))
}
// The super secret combination
const COMBO = [1, 2, 3, 4]
// Whether each digit is correct
const digitCorrect = [false, false, false, false]
for (let i = 0; i < COMBO.length; i++) {
makeLockDigit(value => {
// Digit i has changed, so store whether it is correct
digitCorrect[i] = (value === COMBO[i])
// If all digits are now correct, show a message
if (digitCorrect.every(correct => correct)) {
alert('You got the combination')
}
})
}
```
Since any of the 4 digits might be the last one to become correct, we check whether all of the digits are correct whenever each one changes.
This is generally the case when we don't know what order some asynchronous events will finish in: whenever each one finishes, it needs to check if it was the last one to finish.
There are other ways to store the state of the digits; for example, we could instead track how many are currently correct.
[This version](lock2.html) of the code implements that approach:
```js
// The number of correct digits
let correctCount = 0
for (let i = 0; i < COMBO.length; i++) {
// Whether this digit was previously correct
let wasCorrect = false
makeLockDigit(value => {
// Compare the digit's actual value to the correct value
const isCorrect = (value === COMBO[i])
// Update the number of correct digits if this one changed
if (!wasCorrect && isCorrect) correctCount++
else if (wasCorrect && !isCorrect) correctCount--
wasCorrect = isCorrect
// If all digits are now correct, show a message
if (correctCount === COMBO.length) {
alert('You got the combination')
}
})
}
```
## `setTimeout()`
Another asynchronous JS API is the function `setTimeout()`, which is used to wait for time to pass.
For example, to display a message after 3 seconds (3000 ms), you would write
```js
setTimeout(() => {
console.log('3 seconds have passed')
}, 3000)
```
The fact that `setTimeout()` is asynchronous means it returns immediately, without witing for the time interval.
For example, the following code displays `Timeout started` immediately and `Timeout ended` after 1 second:
```js
setTimeout(() => {
console.log('Timeout ended')
}, 1000)
console.log('Timeout started')
```
As with event handlers, because this API is asynchronous, you can easily wait for multiple intervals of time to pass at the same time.
For example, to create events that will finish 1, 2, ..., 10 seconds from now:
```js
for (let i = 1; i <= 10; i++) {
setTimeout(() => {
console.log(`${i} seconds passed`)
}, i * 1000)
}
```
## Combining asynchronous events in sequence
It is also common to have one asynchronous event that depends on the result of another.
For example, we might want to wait for the user to enter some text, then send it to a server and wait for the server to respond.
In general, this requires us to create the next asynchronous event *inside* the handler for the previous one.
As a concrete example, let's simulate a "random walk" on a grid.
At each step, we randomly move left, right, up, or down, and we count the total number of times we have visited each grid square.
Here is a [first attempt](walk1.html) that only moves 3 times.
```js
// ... (the full code is at the link above)
// Visit a given grid position and
// display the number of times it has been visited
function visit(position) {
// Don't do anything if we're off the grid
const row = grid[position.row]
if (row === undefined) return
const cell = row[position.col]
if (cell === undefined) return
cell.count++
cell.element.innerText = String(cell.count)
}
// Compute the next position by randomly going left, right, up, or down
function nextPosition(position) {
const {row, col} = position
const random = Math.random()
if (random < 0.25) return {row: row + 1, col}
else if (random < 0.5) return {row: row - 1, col}
else if (random < 0.75) return {row, col: col + 1}
else return {row, col: col - 1}
}
// Start in the middle of the grid and jump every DELAY ms
let position = {row: Math.floor(SIZE / 2), col: Math.floor(SIZE / 2)}
visit(position)
setTimeout(() => {
// First movement
position = nextPosition(position)
visit(position)
setTimeout(() => {
// Second movement
position = nextPosition(position)
visit(position)
setTimeout(() => {
// Third movement
position = nextPosition(position)
visit(position)
}, DELAY)
}, DELAY)
}, DELAY)
```
You can see that each sequential delay is represented by nesting another `setTimeout()` inside the last one.
If we want to keep jumping to new squares forever, we need to [rewrite this program using a recursive function](walk2.html):
```js
function walkFrom(position) {
// To perform the walk from the given starting position,
// visit it and then start from the next position after a delay
visit(position)
setTimeout(() => walkFrom(nextPosition(position)), DELAY)
}
// Start in the middle of the grid
walkFrom({row: Math.floor(SIZE / 2), col: Math.floor(SIZE / 2)})
```
## Conclusion
We have seen two examples of asynchronous standard library functions in JavaScript: handling user input and waiting for time.
With both of them, we define a function that we want to get called when something happens.
This structure is common to any asynchronous function; the function passed in to run when it finishes is refered to as the "callback function".
It is up to the browser (or Node.js) to ensure that the callbacks we provide get called at the right times.
We have also looked at some of the primary ways to combine asynchronous actions.
Most programs that interact with a user, read/write files, make web requests, etc. can be broken into actions that run sequentially and in parallel.
Asynchronous programming makes it simple to run actions in parallel or in sequence, although running an action sequentially in a "loop" requires recursion.
<html>
<body>
<button id='alert-button'>Click me!</button>
<script>
// We use the `id` property of the button to access it from JS
const button = document.getElementById('alert-button')
button.onclick = () => {
// You could put any other code you wanted here
// and it would run each time the button is clicked
alert('Button was clicked')
}
</script>
</body>
</html>
<html>
<body>
<div id='lock'></div>
<script>
const lock = document.getElementById('lock')
function makeLockDigit(changeCallback) {
// Make an input that can be set between 0 and 9.
// This is equivalent to <input type='number' min='0' max='9' />.
const digit = document.createElement('input')
digit.type = 'number'
digit.min = 0
digit.max = 9
// Start it with a random value
digit.value = String(Math.floor(Math.random() * 10))
// When the digit changes, call `changeCallback()`,
// passing the new value of the digit.
// Inputs' values are strings, so we convert them to numbers.
digit.onchange = () => changeCallback(Number(digit.value))
// Add the digit to the lock
lock.appendChild(digit)
}
// The super secret combination
const COMBO = [1, 2, 3, 4]
// Whether each digit is correct
const digitCorrect = [false, false, false, false]
for (let i = 0; i < COMBO.length; i++) {
makeLockDigit(value => {
// Digit i has changed, so store whether it is correct
digitCorrect[i] = (value === COMBO[i])
// If all digits are now correct, show a message
if (digitCorrect.every(correct => correct)) {
alert('You got the combination')
}
})
}
</script>
</body>
</html>
<html>
<body>
<div id='lock'></div>
<script>
const lock = document.getElementById('lock')
function makeLockDigit(changeCallback) {
// Make an input that can be set between 0 and 9.
// This is equivalent to <input type='number' min='0' max='9' />.
const digit = document.createElement('input')
digit.type = 'number'
digit.min = 0
digit.max = 9
// Start it with a random value
digit.value = String(Math.floor(Math.random() * 10))
// When the digit changes, call `changeCallback()`,
// passing the new value of the digit.
// Inputs' values are strings, so we convert them to numbers.
digit.onchange = () => changeCallback(Number(digit.value))
// Add the digit to the lock
lock.appendChild(digit)
}
// The super secret combination
const COMBO = [1, 2, 3, 4]
// The number of correct digits
let correctCount = 0
for (let i = 0; i < COMBO.length; i++) {
// Whether this digit was previously correct
let wasCorrect = false
makeLockDigit(value => {
// Compare the digit's actual value to the correct value
const isCorrect = (value === COMBO[i])
// Update the number of correct digits if this one changed
if (!wasCorrect && isCorrect) correctCount++
else if (wasCorrect && !isCorrect) correctCount--
wasCorrect = isCorrect
// If all digits are now correct, show a message
if (correctCount === COMBO.length) {
alert('You got the combination')
}
})
}
</script>
</body>
</html>
<html>
<body>
<table id='grid'></table>
<script>
const SIZE = 30 // width and height of the grid
const DELAY = 500 // delay in ms between steps of the walk
// Build the SIZE x SIZE grid
const table = document.getElementById('grid')
// `grid[i][j]` stores the table cell in row `i` and column `j`,
// as well as the number of times it has been visited during the walk
const grid = []
for (let i = 0; i < SIZE; i++) {
// `tr` is a "table row" element
const rowElement = document.createElement('tr')
const row = []
for (let j = 0; j < SIZE; j++) {
// `td` is a "table cell" element
const element = document.createElement('td')
rowElement.appendChild(element)
row.push({element, count: 0})
}
table.appendChild(rowElement)
grid.push(row)
}
// Visit a given grid position and
// display the number of times it has been visited
function visit(position) {
// Don't do anything if we're off the grid
const row = grid[position.row]
if (row === undefined) return
const cell = row[position.col]
if (cell === undefined) return
cell.count++
cell.element.innerText = String(cell.count)
}
// Compute the next position by randomly going left, right, up, or down
function nextPosition(position) {
const {row, col} = position
const random = Math.random()
if (random < 0.25) return {row: row + 1, col}
else if (random < 0.5) return {row: row - 1, col}
else if (random < 0.75) return {row, col: col + 1}
else return {row, col: col - 1}
}
// Start in the middle of the grid and jump every DELAY ms
let position = {row: Math.floor(SIZE / 2), col: Math.floor(SIZE / 2)}
visit(position)
setTimeout(() => {
// First movement
position = nextPosition(position)
visit(position)
setTimeout(() => {
// Second movement
position = nextPosition(position)
visit(position)
setTimeout(() => {
// Third movement
position = nextPosition(position)
visit(position)
}, DELAY)
}, DELAY)
}, DELAY)
</script>
<style>
#grid {
border-collapse: collapse;
}
#grid td {
border: 1px solid black;
width: 20px;
height: 20px;
font-size: 15px;
font-family: sans-serif;
text-align: center;
}
</style>
</body>
</html>
<html>
<body>
<table id='grid'></table>
<script>
const SIZE = 30 // width and height of the grid
const DELAY = 500 // delay in ms between steps of the walk
// Build the SIZE x SIZE grid
const table = document.getElementById('grid')
// `grid[i][j]` stores the table cell in row `i` and column `j`,
// as well as the number of times it has been visited during the walk
const grid = []
for (let i = 0; i < SIZE; i++) {
// `tr` is a "table row" element
const rowElement = document.createElement('tr')
const row = []
for (let j = 0; j < SIZE; j++) {
// `td` is a "table cell" element
const element = document.createElement('td')
rowElement.appendChild(element)
row.push({element, count: 0})
}
table.appendChild(rowElement)
grid.push(row)
}
// Visit a given grid position and
// display the number of times it has been visited
function visit(position) {
// Don't do anything if we're off the grid
const row = grid[position.row]
if (row === undefined) return
const cell = row[position.col]
if (cell === undefined) return
cell.count++
cell.element.innerText = String(cell.count)
}
// Compute the next position by randomly going left, right, up, or down
function nextPosition(position) {
const {row, col} = position
const random = Math.random()
if (random < 0.25) return {row: row + 1, col}
else if (random < 0.5) return {row: row - 1, col}
else if (random < 0.75) return {row, col: col + 1}
else return {row, col: col - 1}
}
function walkFrom(position) {
// To perform the walk from the given starting position,
// visit it and then start from the next position after a delay
visit(position)
setTimeout(() => walkFrom(nextPosition(position)), DELAY)
}
// Start in the middle of the grid
walkFrom({row: Math.floor(SIZE / 2), col: Math.floor(SIZE / 2)})
</script>
<style>
#grid {
border-collapse: collapse;
}
#grid td {
border: 1px solid black;
width: 20px;
height: 20px;
font-size: 15px;
font-family: sans-serif;
text-align: center;
}
</style>
</body>
</html>
<html>
<body>
<!--
A simple calculator that only supports addition.
It has an input where you can enter a number to add,
a button that can be clicked to add it,
and text that displays the current sum.
-->
<input type='number' id='number' />
<button id='add'>+</button>
<div id='sum'></div>
<!--The JavaScript code that makes the calculator work-->
<script>
// Get the elements declared above in order to interact with them
const numberInput = document.getElementById('number')
const sumDisplay = document.getElementById('sum')
// Show the current value of the `sum` variable in `<div id='sum'>`
function showSum() {
sumDisplay.innerText = String(sum)
}
// The sum starts at 0
let sum = 0
showSum()
// Every time `<button id='add'>` is clicked,
// add the number in `<input id='number'>` to the sum
document.getElementById('add').onclick = () => {
sum += Number(numberInput.value)
showSum()
}
</script>
</body>
</html>
notes/js/colors.png

27.9 KB

// Import the file system module
const fs = require('fs')
if (process.argv.length !== 4) {
throw new Error('Invalid syntax. Usage: node copy.js source destination')
}
// Extract the command line arguments
const source = process.argv[2]
const destination = process.argv[3]
// Read the contents of `source`
fs.readFile(source, (err, data) => {
if (err) throw err
// Write `data` to `destination`, which copies `source` to `destination`
fs.writeFile(destination, data, err => {
if (err) throw err
})
})
notes/js/dev-tools.png

98.8 KB

This diff is collapsed.
const fs = require('fs').promises
let cachedContents
function getContents() {
// If we have already read the file, just return its contents
if (cachedContents !== undefined) {
return Promise.resolve(cachedContents)
}
// Otherwise, read the file and store its contents
const readPromise = fs.readFile('file.txt', 'utf8')
readPromise.then(contents => {
cachedContents = contents
})
return readPromise
}
const start1 = process.hrtime()
getContents().then(_ => {
// Reading file took 1946343 ns
const time1 = process.hrtime(start1)
console.log(`Reading file took ${time1[1]} ns`)
const start2 = process.hrtime()
getContents().then(_ => {
// Using cached file took 29273 ns
const time2 = process.hrtime(start2)
console.log(`Using cached file took ${time2[1]} ns`)
})
})
const fs = require('fs').promises
fs.readFile('a.txt', 'utf8')
.then(aContents => {
// If the contents of a.txt don't end with a newline character,
// reject with an error
if (!aContents.endsWith('\n')) {
throw new Error('Missing newline at end of a.txt')
}
// Otherwise, read b.txt and concatenate the files' contents
return fs.readFile('b.txt', 'utf8')
.then(bContents => Promise.resolve(aContents + bContents))
})
// If either file didn't exist or a.txt didn't end with a newline,
// resolve to the empty string instead
.catch(err => Promise.resolve(''))
// Finally, write the string to c.txt
.then(concatenated => fs.writeFile('c.txt', concatenated))
/*
Note the `.promises`.
`require('fs').promises` has the same functions as `require('fs')`,
but they return Promises instead of taking callbacks.
*/
const fs = require('fs').promises
// Read 'a.txt'. `readPromise` is a `Promise<string>`.
const readPromise = fs.readFile('a.txt', 'utf8')
/*
After `readPromise` finishes, write the result to 'b.txt'.
`contents` will be the `string` that was read.
We return a `Promise<undefined>` that represents the write.
*/
const writePromise = readPromise
.then(contents => fs.writeFile('b.txt', contents))
// Once the write finishes, print a message
writePromise.then(_ => {
console.log('Copying done')
})
const fs = require('fs').promises
const aPromise = fs.readFile('a.txt', 'utf8')
aPromise.then(contents => fs.writeFile('b.txt', contents))
aPromise.then(contents => fs.writeFile('c.txt', contents))
const fs = require('fs')
// The arguments are the file to create and its initial contents.
// Run the program using node create-file.js FILENAME CONTENTS
fs.stat(process.argv[2], err => {
if (err) {
// File didn't exist, so create it
fs.writeFile(process.argv[2], process.argv[3], err => {
if (err) throw err
console.log(`${process.argv[2]} created`)
})
}
else console.log(`${process.argv[2]} already exists`)
})
# Promises
## Passing data to callbacks
In the previous set of notes, we used callbacks as a way to run some code *when* something happens.
However, we often want to know *what* happened.
In this case, we can pass the result of an asychronous action as an argument to the callback function.
We'll look this week at some of the asynchronous functions that make up Node.js's filesystem API.
The full set of functions can be found in the [documentation for the `fs` module](https://nodejs.org/api/fs.html).
There are quite a lot, so we'll look at four of the most useful ones:
- [`fs.readFile()`](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback), used to read the entire contents of a file
- [`fs.writeFile()`](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback), used to set the entire contents of a file
- [`fs.readdir()`](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback), used to list the files in a directory
- [`fs.stat()`](https://nodejs.org/api/fs.html#fs_fs_stat_path_options_callback), used to get metadata about a file (e.g. its size, when it was last modified, etc.)
To illustrate the first two of these, [here](write-echo.js) is an example program that writes to a file and then reads its contents:
```js
// Import Node.js's 'fs' module
const fs = require('fs')
// Write 'hello, world' to the file
fs.writeFile('something.txt', 'hello, world', (err) => {
if (err) throw err
// Now read the file; it should contain 'hello, world' now.
// 'utf8' indicates that the file is a text file encoded in UTF-8.
fs.readFile('something.txt', 'utf8', (err, data) => {
if (err) throw err
// Prints 'hello, world'
console.log(data)
})
})
```
## Callback hell — nesting
You may have noticed that the asynchronous programs above require significantly more code than their synchronous counterparts.
For example, we would write something like this instead in a synchronous language:
```js
writeFile('something.txt', 'hello, world')
console.log(readFile('something.txt', 'utf8'))
```
The general observation that using callbacks tends to make programs more complicated is called "callback hell".
One aspect of callback hell is that, as we saw last time, asynchronous tasks that happen *in sequence* must be nested inside the callbacks of the previous tasks.
For example, [here](size-sum.js) is a program that computes the total size of 3 files:
```js
fs.stat('a.txt', (err, statsA) => {
if (err) throw err
fs.stat('b.txt', (err, statsB) => {
if (err) throw err
fs.stat('c.txt', (err, statsC) => {
if (err) throw err
const totalSize = statsA.size + statsB.size + statsC.size
console.log(`Total size: ${totalSize} bytes`)
})
})
})
```
## Callback hell — error handling
Error handling in asynchronous code is tricky.
Does the following code catch the error that is thrown inside the `setTimeout()` callback?
```js
try {
setTimeout(() => {
throw new Error('Error from timeout')
}, 1000)
}
catch (e) {
console.error(`Error was caught: ${e}`)
}
```
The answer is no.
Remember that `setTimeout()` returns as soon as the callback has been set up, without waiting for the 1 second to elapse.
Therefore, the `try` block ends before the error is thrown.
So how can we "catch" an error that occurs during an asynchronous action?
As you can see in the examples in the previous sections, all of Node.js's asynchronous functions pass an `err` as the first parameter to the callback.
If an error occurred, `err` is set to the `Error` object that was "thrown".
Otherwise, `err` is set to `null`.
For example, `fs.stat()` gives an error if the file we try to read doesn't exist.
We can use this to create a file if it doesn't exist:
```js
// The arguments are the file to create and its initial contents.
// Run the program using node create-file.js FILENAME CONTENTS
fs.stat(process.argv[2], err => {
if (err) {
// File didn't exist, so create it
fs.writeFile(process.argv[2], process.argv[3], err => {
if (err) throw err
console.log(`${process.argv[2]} created`)
})
}
else console.log(`${process.argv[2]} already exists`)
})
```
If we run [this program](create-file.js) using `node create-file.js new-file.txt abc`, it will make the file `new-file.txt` with contents `abc`.
If we run it again with `node create-file.js new-file.txt def`, it won't change the file because it already exists.
But most of the time, we don't want any special error handling.
If an error happens in a sequence of asynchronous actions, we usually want to stop and report an error from the whole sequence.
As you can see in the examples above, writing `if (err) throw err` for every easynchronous action gets quite tedious.
## What is a `Promise`?
In JavaScript, a `Promise` represents an asynchronous task that "promises" to compute a value eventually.
We write `Promise<T>` to denote a `Promise` that will compute a value of type `T`.
This may sound very abstract, so here are some concrete examples:
- Reading a file's contents can be represented as a `Promise<string>`
- Looking up a user in a database can be represented as a `Promise<User>`
- An asynchronous task that *doesn't* compute a value can be represented as a `Promise<undefined>`
It is important to keep in mind that a `Promise<T>` is different from a `T`.
**There is no way to "get" the `T` from a `Promise<T>`**.
When a `Promise` computes a value, this is called "resolving" to the value.
All `Promise`s can also "reject" with an error.
## `Promise` methods
### `.then()`
This method is used to run `Promise`s in sequence.
Because running asynchronous tasks in sequence is extremely common, `.then()` is the primary way to compose `Promise`s.
[Here](copy-promises.js) is how it is used:
```js
/*
Note the `.promises`.
`require('fs').promises` has the same functions as `require('fs')`,
but they return Promises instead of taking callbacks.
*/
const fs = require('fs').promises
// Read 'a.txt'. `readPromise` is a `Promise<string>`.
const readPromise = fs.readFile('a.txt', 'utf8')
/*
After `readPromise` finishes, write the result to 'b.txt'.
`contents` will be the `string` that was read.
We return a `Promise<undefined>` that represents the write.
*/
const writePromise = readPromise
.then(contents => fs.writeFile('b.txt', contents))
// Once the write finishes, print a message
writePromise.then(_ => {
console.log('Copying done')
})
```
In general, if we have a `Promise<A>` and a function `A => Promise<B>`, we can use `.then()` to chain them together into a single `Promise<B>`.
You can call `.then()` multiples times on the same `Promise` if multiple actions need to happen after the `Promise` finishes.
For [example](copy-twice.js), to copy `a.txt` to both `b.txt` and `c.txt`:
```js
const aPromise = fs.readFile('a.txt', 'utf8')
aPromise.then(contents => fs.writeFile('b.txt', contents))
aPromise.then(contents => fs.writeFile('c.txt', contents))
```
### `Promise.resolve()`
This function is used to make a `Promise` that immediately resolves to a given value.
This is useful for a function which sometimes performs an asynchronous action but sometimes returns a pre-computed value.
For [example](cache.js), we can save the contents of a file after reading it the first time:
```js
let cachedContents
function getContents() {
// If we have already read the file, just return its contents
if (cachedContents !== undefined) {
return Promise.resolve(cachedContents)
}
// Otherwise, read the file and store its contents
const readPromise = fs.readFile('file.txt', 'utf8')
readPromise.then(contents => {
cachedContents = contents
})
return readPromise
}
```
### `.catch()`
Error handling with `Promise`s is much easier than with callbacks since `.then()` automatically handles errors that occur.
In [this example](catch-file.js), we concatenate the contents of two files.
If `a.txt` doesn't exist, then `fs.readFile()` will reject and the `aContents => ...` function will never be called.
If `a.txt` doesn't end with a newline, we throw an error, which will also cause the `Promise` to reject.
The `err => ...` function will be called if the `Promise` rejects for any reason.
It reurns a new `Promise` to run instead.
Note that the `concatenated => ...` function will always be called because we catch any error that could have occurred.
```js
fs.readFile('a.txt', 'utf8')
.then(aContents => {
// If the contents of a.txt don't end with a newline character,
// reject with an error
if (!aContents.endsWith('\n')) {
throw new Error('Missing newline at end of a.txt')
}
// Otherwise, read b.txt and concatenate the files' contents
return fs.readFile('b.txt', 'utf8')
.then(bContents => Promise.resolve(aContents + bContents))
})
// If either file didn't exist or a.txt didn't end with a newline,
// resolve to the empty string instead
.catch(err => Promise.resolve(''))
// Finally, write the string to c.txt
.then(concatenated => fs.writeFile('c.txt', concatenated))
```
### `Promise.all()`
`Promise.all()` takes an array of `Promise`s and returns a new `Promise` that resolves once *all* of the `Promise`s have resolved.
When it resolves, it computes an array containing the result of each of the `Promise`s.
In [this example](recursive-mtime.js), we find the most recent modification time of all files inside all subdirectories of a given directory.
(For example, if `a/b/c.txt` was modified, that counts as a modification of `a/b` and `a` as well.)
```js
// Returns a Promise<number> that computes the most recent
// modification time for any file inside a directory
const modifiedTime = path =>
fs.stat(path).then(stats => {
// mtimeMs is the modification time for this file/directory
const {mtimeMs} = stats
if (stats.isDirectory()) {
// If this is a directory, compute the modification time
// for all files/subdirectories inside it
return fs.readdir(path)
.then(files =>
// Compute modification times of all contained files
Promise.all(files.map(file =>
modifiedTime(path + '/' + file)
))
)
// modifiedTimes will be an array containing the latest
// modification time of each file in the directory
.then(modifiedTimes => Math.max(mtimeMs, ...modifiedTimes))
}
// If this is a file, just return its modification time
else return Promise.resolve(mtimeMs)
})
```
## *Aside*: monads
If you've ever used Haskell, you might have noticed that `Promise`s look a lot like its `IO` monad.
`.then()` is the equivalent of `>>=` ("bind"), which chains two IO operations together.
And `Promise.resolve()` is the equivalent of `return`, which wraps a normal value in an instance of `IO`.
Just like monads in Haskell allow you to write code that looks imperative in a functional language, `Promise`s let you write asynchronous programs that look like blocking programs, while still using callbacks under the hood.
Towards the end of the course, we'll also cover JavaScript's `async`-`await` notation, which hides even the calls to `.then()`.
This is very similar to `do` notation in Haskell.
const fs = require('fs').promises
// Returns a Promise<number> that computes the most recent
// modification time for any file inside a directory
const modifiedTime = path =>
fs.stat(path).then(stats => {
// mtimeMs is the modification time for this file/directory
const {mtimeMs} = stats
if (stats.isDirectory()) {
// If this is a directory, compute the modification time
// for all files/subdirectories inside it
return fs.readdir(path)
.then(files =>
// Compute modification times of all contained files
Promise.all(files.map(file =>
modifiedTime(path + '/' + file)
))
)
// modifiedTimes will be an array containing the latest
// modification time of each file in the directory
.then(modifiedTimes => Math.max(mtimeMs, ...modifiedTimes))
}
// If this is a file, just return its modification time
else return Promise.resolve(mtimeMs)
})
modifiedTime('.').then(mTime => {
console.log(`Most recent modification: ${new Date(mTime)}`)
})
const fs = require('fs')
fs.writeFile('a.txt', 'some text', err => {
if (err) throw err
fs.writeFile('b.txt', 'some more text', err => {
if (err) throw err
fs.writeFile('c.txt', 'even more text', err => {
if (err) throw err
fs.stat('a.txt', (err, statsA) => {
if (err) throw err
fs.stat('b.txt', (err, statsB) => {
if (err) throw err
fs.stat('c.txt', (err, statsC) => {
if (err) throw err
const totalSize = statsA.size + statsB.size + statsC.size
console.log(`Total size: ${totalSize} bytes`)
})
})
})
})
})
})
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment