Async/Await Basics in JavaScript

Level 5308 keystrokes

This demonstrates async/await pattern with a simulated delay and data fetching.

JavaScript code

// Helper function that returns a Promise
// setTimeout will resolve the promise after ms milliseconds
1function delay(ms) {
2 return new Promise(resolve => setTimeout(resolve, ms));
3}
4
// async function can contain await expressions
// It always returns a Promise
5async function fetchData() {
6 console.log("Fetching...");
// await pauses execution until the Promise resolves
// Code after await runs after the delay
7 await delay(1000);
8 console.log("Data received!");
// Return value becomes the resolved value of the Promise
9 return { id: 1, name: "Alice" };
10}
11
// Wrapper async function so that await can be used inside it
12async function main() {
// await extracts the resolved value from the Promise
13 const data = await fetchData();
14 console.log(data);
15}
16
// Call the main function
17main();

Output

Fetching...
Data received!
{ id: 1, name: 'Alice' }
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
  • .× 6
  • "× 6
  • {× 4
  • }× 4
  • ,× 2
  • :× 2
  • =× 2

More JavaScript examples at level 5

← JavaScript typing practice