09 async and iterators
Types do not make a promise resolve faster They make the shape of asynchronous code explicit
Table of Contents
Promises
async function fetchText(url: string): Promise<string> {
const response: Response = await fetch(url);
return await response.text();
}
Promise<string> says the eventual value is a string
Calling it without await gives a promise, not a string
That is where most bugs in this area start
async await
await only pauses inside an async function
It unwraps a promise into its value type
Awaiting a non-promise just gives the value back
Response comes from the DOM lib
On Node without DOM types you need the platform’s own typings
Do not assume one set of globals everywhere
Generators
function* iteratePorts(): Generator<number, void, undefined> {
yield 22;
yield 443;
}
Generator<T, TReturn, TNext> describes what is yielded, what is returned, and what can be sent back
Calling iteratePorts().next().value gives number | void
Handle the void case before using the value
Posted