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 Promise
1const fetchData = (id) => {
// Create a new Promise that will resolve with user data
2 return new Promise((resolve) => {
// setTimeout simulates an async operation (like API call)
// After 100ms, resolve with an object containing id and name
3 setTimeout(() => resolve({ id, name: `User${id}` }), 100);
4 });
5};
6
// Start the Promise chain with fetchData(1)
7fetchData(1)
// .then() runs when the Promise resolves
8 .then(user => {
// Log the first user's name
9 console.log(user.name);
// Return another Promise to continue the chain
10 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

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

More JavaScript examples at level 4

← JavaScript typing practice