Async Await Pattern in JavaScript

Level 5275 keystrokes

Async/await provides cleaner syntax for working with promises and asynchronous code.

JavaScript code

// Helper function that returns a promise that resolves after ms milliseconds
1const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
2
// async function allows using await inside
3async function process() {
// Print "Start" immediately
4 console.log("Start");
// await pauses execution until promise resolves
5 await delay(100);
// This runs after 100ms
6 console.log("After 100ms");
// Wait another 100ms
7 await delay(100);
// This runs after total 200ms
8 console.log("After 200ms");
// Return value becomes the resolved value
9 return "Done";
10}
11
// Async functions return promises
// .then() receives the returned value
12process().then(result => console.log(result));

Output

Start
After 100ms
After 200ms
Done
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.

  • (× 11
  • )× 11
  • ;× 8
  • "× 8
  • .× 5
  • =× 4
  • >× 3
  • ,× 1
  • {× 1
  • }× 1

More JavaScript examples at level 5

← JavaScript typing practice