Need to load an image before displaying it, without nesting callbacks? Put `async` before a function and use `await` inside it. The code reads in order, while the work remains asynchronous. `await` gets the value of a resolved promise so the next step can use it. section 32.0 section 32.2
async function fetchImage(url) {
const resp = await fetch(url);
const blob = await resp.blob();
const image = await createImageBitmap(blob);
return image;
};
fetchImage('my-image.png').then(image => {
// do something with image
});
Follow the image through three steps: fetch the URL, turn the response into a blob, then create an ImageBitmap. Each `await` supplies the value needed by the next step. The caller uses `.then` because `fetchImage` returns a promise. section 32.2
An async function always returns a promise. Returning an ordinary value resolves that promise to the value; returning a promise resolves it to that promise’s eventual value. So `fetchImage` can also return `createImageBitmap(blob)` directly instead of awaiting it first. section 32.2
From a promise chain to ordered steps
To render a map, first await `getUserPosition()`, then pass that position to `getDestination(position)` and await the destination. The two assignments make the dependency visible without a chain of `.then` calls. section 32.2
Rejection still matters. If an awaited promise rejects and nothing handles it, the async function’s returned promise rejects. A `try` block around `return Promise.reject(...)` does not catch that rejection in the illustrated case: returning the promise is not the same as awaiting its result there. Handle rejection through the returned promise, or convert each promise into a result-and-error pair with a helper such as `rescue`. section 32.3 section 32.4
Keep the images that loaded
For a photo gallery, start several image requests, attach a handler that collects each success and skips each rejection, then await `Promise.all` on those handled requests. Return the collected images for rendering. This avoids losing the whole gallery when one image fails. section 32.3
Practice: convert a `.then` chain that loads an article, its comments, and its author into an async function. Decide which requests can begin together and which need a value from an earlier request. section 32.4
















