⇧
vadnica-logo
My Services About the Project Telegram O meni O meni

Async and Await in JavaScript

The keywords async and await changed the rules of the game in JavaScript. They don't bring any new underlying technology, but rather what programmers call "syntactic sugar" – meaning they allow us to write asynchronous Fetch code in a way that **looks completely linear and synchronous**, as if reading a standard book from top to bottom.

EXAMPLE
RESULT

Rules of Engagement:

To ensure proper execution, we must follow two golden rules:

  1. async: We place this word right before the function definition (this signals to the browser that the function will operate asynchronously).
  2. await: We place this word before the fetch() call or the data conversion. JavaScript will literally "wait" at that specific line for the server to return the data before moving to the next line.

Error Handling with try ... catch

Since we don't have a .catch() method when using async/await, we catch errors (e.g., if the server goes down) using the classic programming block try { ... } catch (error) { ... } found in other languages:

async function load() {
    try {
        const response = await fetch("data.json");
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("Something went wrong: ", error);
    }
}