How to use async/await?

Asked by ikoholemeje2527 days ago
36 views
Basics of asynchronous programming in JS.
0
1 answers

1 Answer

Async/await is a modern and clean way to handle asynchronous operations in JavaScript, built on top of Promises. It allows you to write asynchronous code that looks and behaves like synchronous code, making it easier to read and maintain. ### How to use async/await 1. **Mark a function as `async`:** To use `await` inside a function, you first declare the function with the `async` keyword. This makes the function return a Promise implicitly. ```javascript async function fetchData() { // code here } ``` 2. **Use `await` to pause execution until a Promise resolves:** Inside an `async` function, you can use `await` before a Promise to wait for it to resolve. The function pauses at this point, and resumes once the Promise settles, returning the resolved value. ```javascript async function fetchData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } ``` 3. **Error handling with try/catch:** Since `await` pauses execution, you can use normal `try/catch` blocks to handle errors, making error handling more straightforward compared to chaining `.catch()` on Promises. ```javascript async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); console.log(data); } catch (error) { console.error('Fetch error:', error); } } ``` 4. **Calling async functions:** Since async functions return Promises, you can either use `.then()` or `await` them from another async function. ```javascript fetchData(); // returns a Promise // Or from another async function async function main() { await fetchData(); console.log('Data fetched'); } main(); ``` ### Summary - Use `async` to declare an asynchronous function. - Use `await` to pause execution until a Promise resolves. - Handle errors with `try/catch`. - Async functions always return a Promise. This pattern makes asynchronous code easier to write and understand compared to traditional Promise chains or callbacks.
0
0
by Jessica Martinez15 days ago