Asynchronous JavaScript
1. Callbacks
function fetchData(callback) {
// Simulate an asynchronous operation (e.g., AJAX request)
setTimeout(function () {
console.log("Data fetched!");
callback();
}, 2000);
}
// Usage
fetchData(function () {
console.log("Callback executed after data is fetched.");
});
2. setTimeout and setInterval
// setTimeout example
setTimeout(function () {
console.log("Delayed execution");
}, 1000);
// setInterval example
let intervalId = setInterval(function () {
console.log("Repeated execution");
}, 1000);
// Stop the interval after 5 seconds
setTimeout(function () {
clearInterval(intervalId);
}, 5000);
3. Promises
It has three states: pending, fulfilled, or rejected.
function fetchData() {
return new Promise(function (resolve, reject) {
// Simulate an asynchronous operation
setTimeout(function () {
console.log("Data fetched!");
resolve(); // Promise is fulfilled
// reject(); // Promise is rejected
}, 2000);
});
}
// Usage
fetchData()
.then(function () {
console.log("Promise fulfilled!");
})
.catch(function () {
console.log("Promise rejected!");
});
4. Async/Await
Async/await is a syntax sugar built on top of promises. The async
keyword is used to define a function that returns a promise, and the await
keyword is used to pause the execution until the promise is resolved.
async function fetchData() {
return new Promise(function (resolve) {
setTimeout(function () {
console.log("Data fetched!");
resolve();
}, 2000);
});
}
// Usage
async function fetchDataAndLog() {
console.log("Start fetching data...");
await fetchData();
console.log("Data fetching complete.");
}
fetchDataAndLog();
5. Fetch API
Using with async
/await
for handling asynchronous data fetching.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
6. Web Worker
Implement background heavy operations such a sorting, heavy calculations, real-time updates, periodic data syncing, ongoing data analysis etc. Workers are executed without blocking the main user interface. Have no access to DOM model.
// main.js
const worker = new Worker('worker.js');
// Send a message to the Worker
worker.postMessage(5); // Calculating factorial of 5
// Listen for messages from the Worker
worker.onmessage = function(event) {
console.log('Factorial calculated:', event.data);
};
// worker.js
// Listen for messages from the main thread
self.onmessage = function(event) {
const number = event.data;
// Calculate the factorial of the number
const result = factorial(number);
// Send the result back to the main thread
self.postMessage(result);
};
// Function to calculate the factorial of a number
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
7. Atomics
, SharedArrayBuffer
, ArrayBuffer
.
Atomics performed on shared memory, which is typically used in the context of Web Workers. The Atomics
object is designed to work with the SharedArrayBuffer
and ArrayBuffer
objects, enabling synchronization and safe manipulation of shared memory across multiple threads.
SharedArrayBuffer
and ArrayBuffer
are objects that represent a block of memory that can be shared between threads.
// In the main thread
const sharedBuffer = new SharedArrayBuffer(4); // 4 bytes for a 32-bit integer
const sharedCounter = new Int32Array(sharedBuffer);
// In the worker thread
const workerCounter = new Int32Array(sharedBuffer);
// Increment the shared counter atomically
Atomics.add(workerCounter, 0, 1);
// Read the shared counter from the main thread
console.log('Main thread counter:', Atomics.load(sharedCounter, 0));