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 milliseconds1function delay(ms) {2 return new Promise(resolve => setTimeout(resolve, ms));3}4 // async function can contain await expressions// It always returns a Promise5async function fetchData() {6 console.log("Fetching..."); // await pauses execution until the Promise resolves // Code after await runs after the delay7 await delay(1000);8 console.log("Data received!"); // Return value becomes the resolved value of the Promise9 return { id: 1, name: "Alice" };10}11 // Wrapper async function so that await can be used inside it12async function main() { // await extracts the resolved value from the Promise13 const data = await fetchData();14 console.log(data);15}16 // Call the main function17main();Output
Fetching...
Data received!
{ id: 1, name: 'Alice' }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