You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
JavaScript is single-threaded, meaning it executes one instruction at a time. Asynchronous programming allows it to handle time-consuming operations — like network requests or file reads — without blocking the rest of the code.
Imagine fetching data from a server. If JavaScript waited for the response before doing anything else, the page would freeze. Async patterns let JavaScript start an operation and continue running other code until the result is ready.
The original async pattern uses callback functions:
setTimeout(function() {
console.log("This runs after 1 second");
}, 1000);
console.log("This runs immediately");
// Output: "This runs immediately", then "This runs after 1 second"
Nested callbacks become hard to read — a pattern called "callback hell":
fetchUser(id, function(user) {
fetchPosts(user.id, function(posts) {
fetchComments(posts[0].id, function(comments) {
// deeply nested — hard to follow
});
});
});
A Promise represents a value that may be available now, in the future, or never:
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Data loaded!");
} else {
reject(new Error("Failed to load data"));
}
});
promise
.then(data => console.log(data)) // "Data loaded!"
.catch(err => console.error(err.message));
Promises can be chained to avoid nesting:
fetchUser(id)
.then(user => fetchPosts(user.id))
.then(posts => fetchComments(posts[0].id))
.then(comments => console.log(comments))
.catch(err => console.error(err));
The async/await syntax (ES2017) makes async code look and feel like synchronous code:
async function loadUserData(userId) {
try {
const user = await fetchUser(userId);
const posts = await fetchPosts(user.id);
const comments = await fetchComments(posts[0].id);
return comments;
} catch (err) {
console.error("Error:", err.message);
}
}
An async function always returns a Promise. The await keyword pauses execution inside the function until the Promise resolves, then returns its value. Other code outside the function continues running normally.
The fetch API is built into modern browsers:
async function getWeather(city) {
try {
const response = await fetch(
"https://api.example.com/weather?city=" + city
);
if (!response.ok) {
throw new Error("HTTP error: " + response.status);
}
const data = await response.json();
console.log(data.temperature);
} catch (err) {
console.error("Failed to fetch weather:", err.message);
}
}
getWeather("London");
// Sequential — waits for each one in turn (slower)
const user = await fetchUser(1);
const settings = await fetchSettings(1);
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.