Skip to content

Latest commit

 

History

History
74 lines (56 loc) · 1.37 KB

File metadata and controls

74 lines (56 loc) · 1.37 KB

Async JavaScript

Promises & Handling Promise-based Methods

A Promise represents a value available now, later, or never.

const p = new Promise((resolve) => {
  setTimeout(() => resolve(123), 10);
});

p.then((v) => console.log("resolved:", v));

Handling errors:

Promise.reject(new Error("boom"))
  .then(() => {
    // skipped
  })
  .catch((err) => {
    console.error("caught:", err.message);
  });

Common helpers:

  • Promise.all (fails fast)
  • Promise.allSettled
  • Promise.race
  • Promise.any

Fetch API (Getting Data using Fetch API)

fetch is available in modern browsers and Node 18+.

const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
console.log(data);

Async & Await

async functions return Promises. await pauses within the async function.

async function getTodo(id) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

getTodo(1)
  .then((todo) => console.log(todo.title))
  .catch((err) => console.error(err));

Try/catch with async:

async function main() {
  try {
    const todo = await getTodo(1);
    console.log(todo);
  } catch (err) {
    console.error("failed:", err.message);
  }
}

main();