Asynchronous JavaScript
Asynchronous:
Handling asynchronous operations in JavaScript entails the usage of callback functions, guarantees, and the async/await syntax.
Let's discover every of those standards:
Callback Functions:
Callback functions are functions that are passed as arguments to another function and are executed later, usually after some asynchronous operation.
function fetchData(callback) {
setTimeout(function() {
const data = 'Hello, World!';
callback(data);
}, 1000);
}
function processResult(result) {
console.log('Processed:', result);
}
fetchData(processResult);
In this example, fetchData simulates an asynchronous operation (e.g., fetching data from a server) and uses a callback function (processResult) to handle the result.
Promises:
Promises provide a cleaner way to handle asynchronous code. A promise represents a value that might be available now, or in the future, or never.
function fetchData() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
const data = 'Hello, World!';
resolve(data); // Fulfill the promise with the data
}, 1000);
});
}
fetchData()
.then(function(result) {
console.log('Resolved:', result);
})
.catch(function(error) {
console.error('Error:', error);
});
In this example, fetchData returns a promise. The then method is used to handle the resolved value, and the catch method is used to handle errors.
Async/Await:
The async/await syntax simplifies working with promises and makes asynchronous code look more like synchronous code.
async function fetchData() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
const data = 'Hello, World!';
resolve(data);
}, 1000);
});
}
async function fetchDataAndProcess() {
try {
const result = await fetchData();
console.log('Resolved:', result);
} catch (error) {
console.error('Error:', error);
}
}
fetchDataAndProcess();
In this example, fetchData returns a promise, and fetchDataAndProcess uses the await keyword to wait for the promise to resolve. The try/catch block handles both successful resolution and errors.
Handling Multiple Promises:
function fetchData(id) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
const data = 'Data for ID ' + id;
resolve(data);
}, 1000);
});
}
// Using Promise.all to handle multiple promises
const promises = [fetchData(1), fetchData(2), fetchData(3)];
Promise.all(promises)
.then(function(results) {
console.log('All resolved:', results);
})
.catch(function(error) {
console.error('Error:', error);
});
Here, Promise. all is used to wait for each of the promises inside the array to be fulfilled. In practice the then method takes an array of results.