notes
notes
async and await are used to handle asynchronous operations in JavaScript in a cleaner and
more readable way, making asynchronous code behave more like synchronous code.
1. async Keyword
Key Points:
The async keyword ensures that the function returns a Promise, even if the function
does not explicitly return a Promise.
It allows for the use of the await keyword inside the function.
Example:
2. await Keyword
Purpose: The await keyword is used inside async functions to pause execution until
a Promise is resolved or rejected.
Behavior: When await is used, the function execution is paused, and JavaScript
waits for the Promise to settle before proceeding.
Promise Resolution: If the Promise resolves successfully, the resolved value is
returned. If the Promise rejects, an error is thrown.
Key Points:
Example:
example();
Key Points:
Example:
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:
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: If a 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.
Summary
async/await helps make JavaScript asynchronous code more manageable and readable by
simplifying the handling of Promises and providing a more synchronous-like flow of
execution.