- Promises are an asynchronous programming pattern introduced in ECMAScript 6 (ES6).
- They represent a value that may not be available yet, but will be resolved or rejected in the future.
- Promises have three states: pending, fulfilled, and rejected.
- The core methods of promises are
finally(), which allow chaining and handling the resolved or rejected values.
- Promises are based on callback functions, but provide a more structured and readable way to handle asynchronous operations.
- Promises are useful for handling single asynchronous operations and allow better error handling and chaining compared to callbacks.
- Async/await is a syntactic sugar built on top of promises, introduced in ECMAScript 2017 (ES8).
- It allows writing asynchronous code in a more synchronous style, making it easier to understand and maintain.
- Async/await is built on top of promises, and any function that returns a promise can be used with async/await.
- Async functions are declared using the
async keyword, and they return a promise.
- Inside async functions, you can use the
await keyword to pause the execution and wait for a promise to resolve before continuing.
- Async/await reduces the nesting of callback functions and provides a more linear flow of code, making it easier to handle errors using traditional try/catch blocks.
Differences between async/await and promises:
1. Syntax: Async/await uses a more synchronous style of coding, making it easier to read and understand. Promises use chaining with
2. Error handling: Async/await allows error handling using traditional try/catch blocks, making it simpler and more familiar. Promises handle errors using the
catch() method, which can be chained after
3. Readability: Async/await code is generally considered more readable and maintainable compared to nested promises.