Promise chain in JavaScript

Level 4193 keystrokes

Chains three then calls on a promise resolved with 10. Each then logs the value it receives and returns double it for the next one, so 10, 20 and 40 are printed.

JavaScript code

// Simulates a data fetch: returns a promise already resolved with 10
1const fetchData = () => Promise.resolve(10);
2
// Starts the chain; each then runs after the previous one finishes
3fetchData()
// The first then receives the resolved value 10
4 .then(num => {
// Prints 10
5 console.log(num);
// The return value 20 becomes the input of the next then
6 return num * 2;
7 })
// The second then receives 20
8 .then(num => {
// Prints 20
9 console.log(num);
// Doubles again and passes 40 on
10 return num * 2;
11 })
// The last then receives 40 and prints it
12 .then(num => console.log(num));

Output

10
20
40
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.

  • (× 9
  • )× 9
  • .× 7
  • ;× 6
  • =× 5
  • >× 4
  • {× 2
  • }× 2
  • *× 2

More JavaScript examples at level 4

← JavaScript typing practice