#javascript #tutorial #intermediate

Day 8: Async JavaScript (Promises & Async/Await)

Day 8: Asynchronous JavaScript

JavaScript is single-threaded. It can do only one thing at a time. But some things take time (downloading a file, reading a database). We don’t want the whole page to freeze while waiting.

1. Callbacks (The Old Way)

Passing a function to be called later.

setTimeout(() => {
    console.log("I run after 2 seconds");
}, 2000);

Problem: “Callback Hell” when doing multiple sequential steps.

2. Promises

A Promise is an object representing specific eventual completion (or failure) of an operation.

const myPromise = new Promise((resolve, reject) => {
    const success = true;
    if (success) resolve("Operation worked!");
    else reject("Something went wrong");
});

myPromise
  .then(data => console.log(data))
  .catch(err => console.error(err));

3. Async / Await (Modern & Clean)

Syntactic sugar over Promises. It looks like synchronous code!

// Function must be marked 'async'
async function fetchData() {
    try {
        const data = await myPromise; // Pauses here until promise resolves
        console.log(data);
    } catch (error) {
        console.log("Error:", error);
    }
}

fetchData();

Homework for Day 8:

  1. Create a function wait(ms) that returns a Promise which resolves after ms milliseconds (use setTimeout inside).
  2. Create an async function run().
  3. Inside run, log “Start”, await wait(2000), then log “Finish”.

Day 9: We connect to the real internet with Fetch API!