Jul 12, 2024
In this two-part tutorial, we learn the essentials of asynchronous programming in JavaScript covering callbacks, promises, async/await
, and the Fetch API. Part 1 introduces concepts and techniques, while Part 2 applies these to build three projects.
Synchronous Programming: Executes tasks sequentially, e.g., Task 1, Task 2, Task 3.
Asynchronous Programming: Allows other processes to run while waiting for tasks to complete (Non-blocking).
setTimeout
to understand asynchronous behavior but leading to callback hell due to nesting.let promise = new Promise((resolve, reject) => {
let condition = true;
if (condition) {
resolve('Success');
} else {
reject('Error');
}
});
then
and catch
:promise.then(value => {
console.log(value); // Success
}).catch(error => {
console.error(error); // Error
});
async/await
await
keyword inside async
functions.async
and await
:async function bakeBrownies() {
await preheatOven();
await mixIngredients();
await bake();
}
try/catch
try {
await someAsyncFunction();
} catch (error) {
console.error('Error:', error);
}
async/await
: Fetch jokes from an API and display on the webpage.async function loadJoke() {
try {
let response = await fetch('https://api.chucknorris.io/jokes/random');
let data = await response.json();
document.getElementById('joke-container').innerText = data.value;
} catch (error) {
console.error('Error:', error);
}
}
async/await
: Get weather data for a city and dynamically update the DOM.async function getWeather(city) {
try {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY`);
const data = await response.json();
updateDOM(data);
} catch (error) {
console.error('Error:', error);
}
}
async/await
: Fetch Pokémon data and display it dynamically.async function getPokemon(name) {
try {
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${name.toLowerCase()}`);
const data = await response.json();
document.getElementById('pokemon-image').src = data.sprites.front_default;
} catch (error) {
console.error('Error:', error);
}
}
async/await
for cleaner and more maintainable code.