async
and await
are features in JavaScript (and TypeScript) that work together to simplify asynchronous code and make it look more like synchronous code. Here's a clear explanation of each:
async Function
The async
keyword is used to define asynchronous functions. An async function is a function that operates asynchronously via the event loop, allowing other code to run in parallel while waiting for the asynchronous operation to complete.
Syntax: An async function is declared using the
async
keyword before the function declaration.javascriptasync function fetchData() { // Async operations go here }
Return Value: Async functions always return a Promise. If a value is explicitly returned from within the function, the Promise will resolve with that value. If an exception is thrown, the Promise will be rejected with the thrown value.
Usage: Async functions are typically used when dealing with asynchronous operations such as fetching data from a server, reading files, or any operation that involves waiting for some external event to complete.
await Operator
The await
keyword is used within async functions to pause execution and wait for a Promise to resolve. It can only be used inside async functions.
Syntax:
await
is placed before a Promise-based function call or any expression that returns a Promise.javascriptasync function fetchData() { let result = await fetch('https://api.example.com/data'); let data = await result.json(); return data; }
Behavior: When
await
is used, the async function pauses execution until the Promise is resolved or rejected. This allows the async function to wait for the asynchronous operation to complete without blocking the execution of other code.Error Handling: To handle errors when using
await
, you can usetry...catch
blocks around theawait
statements. If the awaited Promise rejects, the error will be thrown, and you can catch it.
Example
Here's a simplified example demonstrating the use of async
and await
:
javascriptasync function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Failed to fetch data');
}
let data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error; // Re-throw the error to propagate it
}
}
// Using fetchData
fetchData()
.then(data => console.log('Data fetched:', data))
.catch(error => console.error('Fetch error:', error));
Summary
- async: Defines asynchronous functions that return a Promise.
- await: Pauses execution within async functions until Promises are resolved or rejected.
- Together,
async
andawait
make asynchronous code more readable and easier to write, especially when dealing with multiple asynchronous operations or handling errors.
By using async
and await
, you can write cleaner and more maintainable asynchronous JavaScript code that behaves more predictably and synchronously at the surface level, even though it operates asynchronously under the hood.
Comments
Post a Comment