Skip to main content

10. Asynchronous JavaScript

JavaScript is single-threaded, but it can handle multiple tasks at once using asynchronous code. This is essential for web apps that fetch data, wait for user input, or use timers.


10.1 Basics

What is Asynchronous JS?

Code that runs later, without blocking the main thread. Used for network requests, timers, and more.


10.2 Callbacks

Callback Functions

Function passed as an argument to run after something finishes.

setTimeout(() => {
console.log('Done!');
}, 1000);

Callback Hell

Nested callbacks can get messy:

doA(() => {
doB(() => {
doC(() => {
// ...
});
});
});

10.3 Promises

Promises represent a value that may be available now, later, or never.

let p = new Promise((resolve, reject) => {
setTimeout(() => resolve('OK'), 1000);
});
p.then(result => console.log(result));

States

  • pending: Not finished
  • resolved: Success
  • rejected: Error

10.4 Async / Await

Syntactic sugar for working with promises. Makes async code look synchronous.

async function fetchData() {
try {
let res = await fetch('https://api.example.com');
let data = await res.json();
console.log(data);
} catch (e) {
console.error(e);
}
}
fetchData();

Next: Error Handling