errors and async

JSON.parse("{bad") throws I caught it and printed a clean message Nothing about that is clever , it is just the correct shape

try and catch

try {
  JSON.parse("{bad");
} catch (err) {
  console.error("bad data", err instanceof Error);
}

Catch the error you expect Let everything else surface

Promises

const done = await Promise.resolve("done");
console.log(done);

Output:

done

await unwraps a promise Outside an async function it requires module context

async await

async function fetchValue() {
  return await Promise.resolve(42);
}

An async function always returns a promise Returning a plain value from it still gives a promise to the caller

Composition

const values = await Promise.all([
  Promise.resolve(1),
  Promise.resolve(2)
]);

Output:

[1, 2]

Promise.all fails fast if one promise rejects Promise.allSettled waits for every outcome Pick based on whether partial results are useful

Next

Copyable patterns in 10 recipes

Posted