
Asynchronous JavaScript is a programming paradigm that allows for non-blocking execution of code, which is essential for building modern web applications. In this guide, we will explore three key concepts of asynchronous JavaScript: Promises, Async/Await, and Callbacks, with examples to demonstrate how each works.
1. Promises:
Promises are a type of object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. With Promises, we can chain multiple asynchronous operations together and handle errors gracefully.
Example:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
let randomNum = Math.floor(Math.random() * 101);
if (randomNum % 2 === 0) {
resolve(randomNum);
} else {
reject('Error: number is odd');
}
}, 1000);
});
myPromise.then((result) => {
console.log(`The random number is: ${result}`);
}).catch((error) => {
console.log(error);
});
In this example, we create a Promise that generates a random number between 0 and 100. If the number is even, the Promise resolves with the random number. If the number is odd, the Promise rejects with an error message. We then use the .then() method to handle the resolved value, and the .catch() method to handle any errors thrown.
2. Async/Await:
Async/Await is a newer feature in JavaScript that allows us to write asynchronous code that looks more like synchronous code, making it easier to read and maintain.
Example:
const myAsyncFunction = async () => {
try {
let result1 = await myPromiseFunction();
let result2 = await myPromiseFunction();
console.log(`The results are: ${result1} and ${result2}`);
} catch(error) {
console.log(error);
}
}
myAsyncFunction();
In this example, we create an async function that uses the await keyword to wait for the values returned by myPromiseFunction() to resolve before moving on to the next line of code. We handle errors using a try/catch block.
3. Callbacks:
Callbacks are functions that are passed as arguments to other functions and executed once the first function has completed its task. They have been used for many years in JavaScript to handle asynchronous code.
Example:
const myCallbackFunction = (err, result) => {
if(err) {
console.log(err);
} else {
console.log(`The result is ${result}`);
}
}
const myAsyncFunctionWithCallback = (callback) => {
setTimeout(() => {
let randomNum = Math.floor(Math.random() * 101);
if (randomNum % 2 === 0) {
callback(null, randomNum);
} else {
callback('Error: number is odd', null);
}
}, 1000);
}
myAsyncFunctionWithCallback(myCallbackFunction);
In this example, we create a callback function myCallbackFunction that is passed as an argument to myAsyncFunctionWithCallback. The asynchronous function generates a random number, and if it’s even, it passes the value to the callback function. If it’s odd, it passes an error message. The myCallbackFunction function handles the callback by checking for errors and printing the result if there are none.
In conclusion, understanding Promises, Async/Await, and Callbacks is essential for mastering asynchronous JavaScript. Each concept has its own advantages and disadvantages, and knowing when to use each one will make your code more efficient and maintainable.
