Science Knowings: JavaScript Course For Social Media

Promises

Previously on Promises

In our previous session, we covered async/await, a powerful mechanism to work with asynchronous operations in a synchronous way.


Today, let's dive into Promises, another important concept in JavaScript for handling asynchronous tasks.

What are Promises?

Promises are objects that represent the eventual completion (or failure) of an asynchronous operation.


They provide a way to handle the result of an asynchronous operation in a synchronous manner, making it easier to write asynchronous code.

Why We Use Promises

Promises offer several advantages over traditional callback-based approaches:


  1. Improved readability and maintainability of asynchronous code.
  2. Error handling is simplified and more efficient.
  3. Promises can be chained, allowing for more complex asynchronous operations.

Concept of Async/Await

Async/await is a syntactic sugar built on top of Promises.


It allows you to write asynchronous code in a synchronous-looking manner, making it even more convenient to handle asynchronous operations.

Advantage and Disadvantage of Promises

Advantages:

  1. Improves code readability and maintainability.
  2. Simplifies error handling.
  3. Supports chaining, allowing for complex asynchronous operations.

Disadvantage:

  1. Can lead to more verbose code compared to callbacks.

Syntax of Promises

new Promise((resolve, reject) => {...})

The resolve function is called when the operation completes successfully, passing the result as an argument.

The reject function is called when the operation fails, passing the error as an argument.

Difference Between Callback vs Promis

CallbackPromise
Involves passing a callback function as an argument to an asynchronous function.Returns a Promise object representing the eventual completion or failure of the operation.
Harder to handle errors and chaining of multiple asynchronous operations.Provides built-in error handling and chaining capabilities.
Less readable and maintainable code.Improves code readability and maintainability.

How To Use Promises

To use Promises, you create a new Promise object and pass it an executor function.


The executor function takes two arguments: resolve and reject.


When the asynchronous operation is complete, you call either resolve with the result or reject with the error.

Resolving and Rejecting Promises

Resolve:
resolve(result)
Triggers the .then() method and passes the result to its callback function.


Reject:
reject(error)
Triggers the .catch() method and passes the error to its callback function.

Handling Promise Errors

Promises provide a .catch() method to handle errors.


promise.catch(error => {...})


This method is called when the Promise is rejected and allows you to handle the error gracefully.

Chaining Promises

Promises can be chained to handle multiple asynchronous operations.


promise.then(result => {...}).then(result2 => {...})


Each .then() returns a new Promise, allowing you to chain multiple asynchronous operations together.

Common Promise Methods

MethodDescription
resolveTriggers the .then() method.
rejectTriggers the .catch() method.
thenReturns a new Promise and triggers a callback when the Promise is resolved.
catchTriggers a callback when the Promise is rejected.
finallyExecutes a callback regardless of whether the Promise is resolved or rejected.

Handling Multiple Promises

To handle multiple Promises at once, you can use:


  1. Promise.all(): Waits for all Promises to settle (resolve or reject) and returns an array of results or a single error if any Promise rejects.
  2. Promise.race(): Returns the result of the first Promise to settle.
  3. Promise.any()(ES2021): Similar to Promise.race(), but returns the first fulfilled Promise (not rejected).

Promise.all()

Promise.all([promise1, promise2, ...])


Returns a new Promise that resolves when all of the input Promises have resolved.


If any of the Promises reject, the returned Promise will reject with the error from the first rejected Promise.

Promise.race()

Promise.race([promise1, promise2, ...])


Returns a new Promise that resolves or rejects as soon as one of the input Promises resolves or rejects.


If all Promises reject, the returned Promise will reject with an AggregateError.

Promise.any() (ES2021)

Promise.any([promise1, promise2, ...])


Returns a new Promise that resolves as soon as one of the input Promises resolves.


If all Promises reject, the returned Promise will reject with an AggregateError.

Next Topic: Fetch API

In our next session, we will dive into the Fetch API.


The Fetch API provides a modern and simplified way to make HTTP requests in JavaScript.


Follow us to learn more!