1. Fetching Data from an API
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("Failed to load data", error);
}
}
Use Case: Retrieve data from a server and await its arrival before processing.
2. Reading Files in Node.js
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
} catch (error) {
console.error("Failed to read file", error);
}
}
Use Case: Read a file asynchronously without blocking, handling the result as soon as it's available.
3. Chaining Asynchronous Operations
async function fetchMultipleData() {
try {
const [data1, data2] = await Promise.all([
fetch('https://api.example.com/data1').then(res => res.json()),
fetch('https://api.example.com/data2').then(res => res.json())
]);
console.log(data1, data2);
} catch (error) {
console.error("Failed to fetch data", error);
}
}
Use Case: Perform a series of dependent asynchronous operations, handling each in turn.
4. User Authentication Flow
async function loginUser(email, password) {
try {
// Simulate network request
const response = await 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);
});
console.log('User logged in', response);
} catch (error) {
console.error(error.message);
}
}
Use Case: Handle user authentication, waiting for and reacting to the outcome.
5. Chaining Asynchronous Operations
async function processDataFlow() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
const processedData = await processData(data);
console.log(processedData);
} catch (error) {
console.error("Failed in processing", error);
}
}
Use Case: Perform a series of dependent asynchronous operations, handling each in turn.
6. Image Preloading
async 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;
});
}
async function useImage(url) {
try {
const image = await loadImage(url);
document.body.appendChild(image);
} catch (error) {
console.error(error.message);
}
}
Use Case: Load an image and use it in the document once fully loaded.
7. Handling Asynchronous Loops
async function processArray(array) {
for (const item of array) {
await processItem(item);
}
}
Use Case: Process items in an array one by one, waiting for each asynchronous operation before moving to the next.
8. Database Operations in Node.js
const { Pool } = require('pg');
const pool = new Pool();
async function queryDatabase() {
try {
const res = await pool.query('SELECT * FROM users WHERE id = $1', [1]);
console.log(res.rows[0]);
} catch (error) {
console.error('Query error', error.stack);
}
}
Use Case: Perform and await the result of a database query.