Promise Chaining in JavaScript
Level 4244 keystrokes
Chains multiple Promise operations using .then() to handle sequential async tasks.
JavaScript code
// Define a function that returns a Promise1const fetchData = (id) => { // Create a new Promise that will resolve with user data2 return new Promise((resolve) => { // setTimeout simulates an async operation (like API call) // After 100ms, resolve with an object containing id and name3 setTimeout(() => resolve({ id, name: `User${id}` }), 100);4 });5};6 // Start the Promise chain with fetchData(1)7fetchData(1) // .then() runs when the Promise resolves8 .then(user => { // Log the first user's name9 console.log(user.name); // Return another Promise to continue the chain10 return fetchData(2);11 }) // This .then() receives the result of fetchData(2)12 .then(user => console.log(user.name));Output
User1 User2
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.
(× 12)× 12;× 6.× 6=× 6{× 5}× 5>× 5,× 2`× 2