← العودة إلى الدورة: JavaScript from scratch

async/await, fetch and error handling

الفيديو قريبًا

Promises solve callback hell, but .then chains are still less natural than normal code. That is why ES2017 added async/await, a syntax that lets you write asynchronous code that looks synchronous. It does not replace promises: it is a more comfortable way to consume them. A function marked async always returns a promise, and inside it the word await pauses the function until the promise resolves, without blocking the rest of the program.

javascript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function greetLater(name) {
  await wait(200);
  return `Hello, ${name}`;
}

async function main() {
  const message = await greetLater('Ana');
  console.log(message); // Hello, Ana

  // Sequential: ~400 ms
  const a = await greetLater('A');
  const b = await greetLater('B');

  // Parallel: ~200 ms
  const [c, d] = await Promise.all([greetLater('C'), greetLater('D')]);
  console.log(a, b, c, d);
}

main();

Errors with try...catch

With async/await errors are handled with the good old try...catch. If a promise you await is rejected, an exception is thrown on that line and the catch block catches it. The finally block always runs and is ideal for cleanup tasks, such as hiding a loading indicator. A very common mistake is forgetting await: you get a promise instead of the value, and your code tries to use it as if it were the result. Another is using await inside a forEach, which does not wait; use a for...of.

fetch: requesting data from a server

The fetch(url) function makes an HTTP request and returns a promise that is fulfilled with a Response object. It works in all modern browsers and in Node.js 22 without installing anything. There is an important trap: fetch only rejects on network failures; a 404 or 500 response is NOT an error for fetch. You must check response.ok (true for status codes 200 to 299) and throw the error yourself. Then, response.json() reads the body as JSON and also returns a promise, so it needs its own await.

javascript
async function getTodo(id) {
  const url = `https://jsonplaceholder.typicode.com/todos/${id}`;
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`HTTP error ${response.status}`);
  }
  return response.json();
}

async function main() {
  try {
    const todo = await getTodo(1);
    console.log(todo.title);
    await getTodo(99999); // this one returns 404
  } catch (error) {
    console.log('Failed:', error.message); // Failed: HTTP error 404
  } finally {
    console.log('Request finished');
  }
}

main();

To send data, pass a second argument with method, headers and body, where the body is the JSON converted with JSON.stringify. In a real application it is also good to show the user a loading state and a clear message if something fails, instead of leaving the error only in the console. Keep in mind that browsers apply CORS: a server must explicitly allow another website to make requests to it.

javascript
async function createPost(data) {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  });
  if (!response.ok) throw new Error(`HTTP error ${response.status}`);
  return response.json();
}

createPost({ title: 'Hello', body: 'First post', userId: 1 })
  .then((created) => console.log('Created id:', created.id))
  .catch((error) => console.log('Error:', error.message));

Loading states and good practices

When an application requests data, the user needs to know what is happening. A simple pattern is to show a Loading message before the request, hide it in the finally block and show an error message inside catch. That way the interface is never left in a confusing state, whatever happens. Also, do not blindly trust the data that arrives: check that the fields you are going to use exist. And if the user can trigger the same request several times in a row, disable the button while you wait to avoid duplicates.

javascript
const statusEl = document.querySelector('#status');
const button = document.querySelector('#load');

button.addEventListener('click', async () => {
  button.disabled = true;
  statusEl.textContent = 'Loading...';
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    if (!response.ok) throw new Error(`HTTP error ${response.status}`);
    const todo = await response.json();
    statusEl.textContent = todo.title;
  } catch (error) {
    statusEl.textContent = `Something went wrong: ${error.message}`;
  } finally {
    button.disabled = false;
  }
});

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →