1. Loading Data from an API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Failed to load data", error));
Use Case: Fetch data from a remote server and process it when available.
2. File Reading in Node.js
const fs = require('fs').promises;
fs.readFile('example.txt', 'utf8')
.then(data => console.log(data))
.catch(error => console.error("Failed to read file", error));
Use Case: Read a file without blocking the main thread, processing its content upon completion.
3. Waiting for Multiple Requests to Complete
Promise.all([
fetch('https://api.example.com/data1'),
fetch('https://api.example.com/data2')
]).then(responses => {
return Promise.all(responses.map(res => res.json()));
}).then(data => console.log(data));
Use Case: Execute multiple API calls simultaneously and wait for all of them to complete.
4. User Authentication
function loginUser(email, password) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (email === 'user@example.com' && password === 'password123') {
resolve({ userId: 1, profile: "User Profile" });
} else {
reject(new Error("Authentication failed"));
}
}, 1000);
});
}
Use Case: Simulate user login, resolving on success and rejecting on failure.
5. Data Processing Pipeline
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => processData(data))
.then(processedData => console.log(processedData))
.catch(error => console.error("Failed in processing pipeline", error));
function processData(data) {
// Process data
return modifiedData;
}
Use Case: Chain operations where each step depends on the successful completion of the previous one.
6. Image Loading
function loadImage(url) {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = () => reject(new Error('Failed to load image'));
image.src = url;
});
}
Use Case: Load an image and perform actions once it is fully loaded or handle errors if it fails to load.
7. Asynchronous Loops
async function processArray(array) {
for (const item of array) {
await processItem(item);
}
}
Use Case: Sequentially process items in an array, waiting for each asynchronous operation to complete before continuing.
8. Database Queries in Node.js
const { Pool } = require('pg');
const pool = new Pool();
pool.query('SELECT * FROM users WHERE id = $1', [1])
.then(res => console.log(res.rows[0]))
.catch(e => console.error('Query error', e.stack));
Use Case: Execute a database query and process the results asynchronously.
9. Timeouts
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
delay(1000).then(() => console.log("Delayed for 1 second"));
Use Case: Execute some action after a delay, without blocking the main thread.Animation Sequence
10. Animation Sequences
function animateElement(element, animation) {
return new Promise(resolve => {
element.classList.add(animation);
element.addEventListener('animationend', resolve, { once: true });
});
}
Use Case: Perform animations on elements sequentially, waiting for one to finish before starting another.