Interview question
How do you run asynchronous operations in parallel vs sequentially using async/await? async/await से asynchronous operations parallel vs sequentially कैसे चलाएं?
Answer
Using await one after another runs operations sequentially (each waits for the previous). Starting all promises first and awaiting together runs them in parallel.
function delay(value, ms) {
return new Promise(resolve => setTimeout(() => resolve(value), ms));
}
// SEQUENTIAL - takes 3 seconds total (1+1+1)
async function sequential() {
console.time('sequential');
const a = await delay('A', 1000);
const b = await delay('B', 1000);
const c = await delay('C', 1000);
console.timeEnd('sequential'); // ~3000ms
return [a, b, c];
}
// PARALLEL - takes 1 second total (all run concurrently)
async function parallel() {
console.time('parallel');
const promiseA = delay('A', 1000); // starts immediately, not awaited yet
const promiseB = delay('B', 1000); // starts immediately too
const promiseC = delay('C', 1000); // starts immediately too
const results = await Promise.all([promiseA, promiseB, promiseC]);
console.timeEnd('parallel'); // ~1000ms
return results;
}
// Use sequential when operations DEPEND on each other
async function dependent() {
const user = await getUser(1); // must finish first
const orders = await getOrders(user.id); // needs user.id
return orders;
}
// Use parallel when operations are INDEPENDENT
async function independent() {
const [users, products] = await Promise.all([
getUsers(), // doesn't depend on products
getProducts() // doesn't depend on users
]);
return { users, products };
}Await को एक के बाद एक इस्तेमाल करने से operations sequentially चलते हैं। सभी promises पहले शुरू करके साथ await करने से parallel चलते हैं।
function delay(value, ms) {
return new Promise(resolve => setTimeout(() => resolve(value), ms));
}
// SEQUENTIAL - कुल 3 सेकंड
async function sequential() {
const a = await delay('A', 1000);
const b = await delay('B', 1000);
const c = await delay('C', 1000);
return [a, b, c];
}
// PARALLEL - कुल 1 सेकंड
async function parallel() {
const promiseA = delay('A', 1000);
const promiseB = delay('B', 1000);
const promiseC = delay('C', 1000);
const results = await Promise.all([promiseA, promiseB, promiseC]);
return results;
}
// Dependent operations - sequential
async function dependent() {
const user = await getUser(1);
const orders = await getOrders(user.id);
return orders;
}
// Independent operations - parallel
async function independent() {
const [users, products] = await Promise.all([
getUsers(),
getProducts()
]);
return { users, products };
}Was this answer clear?