Next →

Asynchronous JavaScript: Callbacks and Promises

JavaScript runs code asynchronously to handle tasks like fetching data without blocking the main thread.

Callbacks

A callback is a function passed into another function to run once an operation completes.

function fetchData(callback) {
  setTimeout(() => {
    callback("Data loaded");
  }, 1000);
}

fetchData(function(message) {
  console.log(message);
});

Promises

Promises provide a cleaner way to handle async operations, representing a future value.

let promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Success!");
  }, 1000);
});

promise.then(result => {
  console.log(result);
});