How do you work with asynchronous JavaScript?
sobes.tech AI
Answer from AI
I work with asynchronous JavaScript using callbacks, promises, and async/await.
Callbacks are functions passed as arguments to other functions and executed after a certain operation completes. They can lead to "callback hell" when nested.
// Example of a callback
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData((data) => {
console.log(data); // Will output "Data received" after 1 second
});
Promises are objects representing the eventual completion or failure of an asynchronous operation. They simplify working with async code and help avoid deep nesting. They have three states: pending, fulfilled, and rejected.
// Example of a promise
function fetchDataPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
}, 1000);
});
}
fetchDataPromise()
.then((data) => {
console.log(data); // Will output "Data received" after 1 second
})
.catch((error) => {
console.error("Error:", error);
});
Async/await is syntactic sugar over promises that makes asynchronous code more readable, similar to synchronous code. A function marked with async always returns a promise. The await operator can only be used inside async functions and pauses execution until the promise is resolved or rejected.
// Example of async/await
async function fetchDataAsync() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
}, 1000);
});
}
async function processData() {
try {
const data = await fetchDataAsync();
console.log(data); // Will output "Data received" after 1 second
} catch (error) {
console.error("Error:", error);
}
}
processData();
I often use async/await when working with API requests, as it is the most convenient and readable way to handle asynchronous operations. For parallel execution of multiple async operations, I use Promise.all() or Promise.allSettled().
I use the event loop to understand the order of asynchronous code execution, microtasks, and macrotasks.