Async/Await with Try-Catch in JavaScript

Level 4208 keystrokes

Async/await with try-catch provides clean syntax for handling asynchronous operations and their errors.

JavaScript code

// Define an async function
1async function fetchUser() {
// Try block for error handling
2 try {
// await waits for the promise and returns its value
3 const response = await Promise.resolve({ name: "John" });
// Log the user name from response
4 console.log(response.name);
// Catch block handles any errors
5 } catch (error) {
// Log the error if one occurs
6 console.log(error);
// Finally block always executes
7 } finally {
// Log completion message
8 console.log("Done");
9 }
10}
// Call the async function
11fetchUser();

Output

John
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.

  • (× 7
  • )× 7
  • ;× 5
  • .× 5
  • {× 5
  • }× 5
  • "× 4
  • :× 1
  • =× 1

More JavaScript examples at level 4

← JavaScript typing practice