• await pauses the function execution until a Promise is resolved, which can lead to
sequential execution.
• However, multiple asynchronous operations can be executed in parallel by calling
multiple Promises and using Promise .all ().
Key Points:
• Promise. all ( ) : This
method ensures that all promises execute concurrently and only
resolves when all promises have resolved.
Example:
async function fetchData() { const userData = await
fetch( 'https ://[Link]/users');
const postData = await
fetch( 'https ://jsonplacehol [Link]/posts' );
const [users, posts] = await [Link] ([userData .json(),
[Link]() ]);
[Link](users, posts);
fetchData ();
6. Important Considerations
• Blocking:Although await waits for promises, it only blocks the execution of the code
inside the async function. Other asynchronous tasks continue in parallel.
• await and Non-Promise Values: Ifa non-Promise value is passed to await,it is treated as
a resolved Promise immediately.
• Return Value of async Functions: The return value of an async function is always a
Promise, even if it doesn't explicitly return one.
• Benefits of Using asynclawait
• Improved Readability:Asynchronous code using async/await looks more like
synchronous code, making it easier to read and understand.
• Error Handling:Easier to handle enors in asynchronous code through try ...catch
blocks, similar to synchronous code.
• Cleaner Code:Eliminates the need for complex chaining of then ()and catch ()that is
common with Promises.
Summary
• async: Marks a function as asynchronous, making it return a Promise.
• await: Pausesthe execution of an async function until the Promise resolves or rejects.
• Error Handling:async/await simplifies enor handling using try ...catch.
• Parallel Execution : Promise .all() can be used to execute multiple asynchronou s
tasks in parallel.