Promise.all Parallel in JavaScript
Level 5421 keystrokes
This uses Promise.all to fetch multiple resources in parallel.
JavaScript code
// Simulate fetching a user by ID// Returns a Promise that resolves after 100ms1function fetchUser(id) {2 return new Promise(resolve => {3 setTimeout(() => resolve({ id, name: `User${id}` }), 100);4 });5}6 // Fetch multiple users in parallel7async function fetchAllUsers(ids) {8 console.log("Fetching users..."); // map creates an array of Promises (all start immediately) // Each fetchUser call runs concurrently, not sequentially9 const promises = ids.map(id => fetchUser(id)); // Promise.all waits for ALL promises to resolve // Returns an array of results in the same order as input10 const users = await Promise.all(promises);11 return users;12}13 // Main function to run the example14async function main() { // Fetch users with IDs 1, 2, 3 in parallel // Total time ~100ms instead of ~300ms if sequential15 const users = await fetchAllUsers([1, 2, 3]); // Print each user's name16 users.forEach(u => console.log(u.name));17}18 19main();Output
Fetching users... User1 User2 User3
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
(× 15)× 15;× 9.× 9=× 7{× 6}× 6,× 4>× 4"× 2