본문으로 건너뛰기

Async/Await for Asynchronous Processing

Async/Await for Asynchronous Processing

async and await are syntactic features in JavaScript that make asynchronous processing easier and cleaner.

Using promises with .then() and .catch() to chain callback functions can make the code complex and reduce readability.

async/await addresses this issue and helps you write asynchronous code as if it were synchronous.


Example

JavaScript
async function fetchUserData() {
try {
let response = await fetch('https://api.example.com/user');
let data = await response.json();
console.log(data);
} catch (error) {
console.log('Failed to fetch data:', error);
}
}

fetchUserData();

In the example above, async is a keyword for declaring an asynchronous function, and await is a keyword that waits for and returns the result of a promise.

If there is an issue with the fetch call or parsing the data, the error is handled in the catch block.


Characteristics

  1. Asynchronous Function: Declaring a function with async always returns a promise.

  2. Error Handling: Errors can be easily handled using try/catch blocks.


How would you explain it with a metaphor?

Think of async/await as waiting for the food you've ordered?

  • Just as you order food at a restaurant and wait for it to be served, await waits until the result is ready.

  • If there's a problem while the food is being prepared, you're informed right away, just as you can find out immediately when there's an issue using a try/catch block.