JavaScript Intermediate Day 6: Asynchronous JavaScript

Goal of this Day

Today you will learn:

By the end, you will be able to manage time-dependent operations and API calls in JavaScript.

Step 1: setTimeout

Run code after a delay:


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

Step 2: Promises

Promises represent a value that may be available now or in the future:


const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Data loaded"), 2000);
});

promise.then(console.log); // "Data loaded" after 2s

Step 3: async / await

Simpler syntax to handle promises:


async function getData() {
  return "Data loaded";
}

getData().then(console.log); // "Data loaded"

Practice


async function getData() {
  return "Data loaded";
}

getData().then(console.log);

Task

Create a promise that resolves after 2 seconds:


const waitTwoSeconds = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Resolved after 2 seconds"), 2000);
});

waitTwoSeconds.then(console.log);