Promises | Ep 02  Season 02 - Namaste JavaScript

Promises | Ep 02 Season 02 - Namaste JavaScript

Understanding Promises in JavaScript

Importance of Promises

  • Promises are crucial for JavaScript developers, especially for frontend interviews where questions about promises are common.
  • A deep understanding of promises not only aids in interviews but also enhances day-to-day coding skills.

Overview of the Video

  • The video aims to explore the concept of promises thoroughly, emphasizing their beauty and functionality.
  • The presenter will illustrate how asynchronous operations were handled before and after the introduction of promises using a practical example.

Example Scenario: E-commerce Website

  • An e-commerce website is used as an example, with a cart represented as an array containing items like shoes and pants.
  • Two APIs are introduced:
  • Create Order API: Takes cart items and returns order details or an order ID.
  • Proceed to Payment API: Requires the order ID to proceed with payment.

Challenges with Callbacks

  • Both APIs are asynchronous, meaning their execution time is uncertain and they depend on each other.
  • The traditional method of handling these operations involved callbacks, which could lead to issues such as inversion of control.

Inversion of Control Issue

  • By passing callback functions to APIs, developers relinquish control over when or if those callbacks will be executed.
  • This reliance on external code can lead to risks; for instance, if the Create Order API fails to call back or calls it multiple times unexpectedly.

Transitioning to Promises

  • To address these issues, APIs should be designed to return promises instead of accepting callback functions.
  • A promise acts as a placeholder for future data that will eventually be returned by the asynchronous operation (e.g., Create Order API).

Understanding Promises Further

Understanding Promises in JavaScript

What is Undefined and Empty Value?

  • The concept of "undefined" refers to a variable that has been declared but not assigned a value, while an empty value indicates the absence of any data. In this context, it suggests that the program will initially return an empty object with some properties.

How Promises Work

  • When the createOrder API is called, it returns a promise which acts as a placeholder for future data (order details).
  • The promise starts as an empty object and will eventually be filled with order details after some asynchronous operation completes.

Attaching Callbacks to Promises

  • Once the order details are available, we can continue our program by attaching a callback function to the promise using .then().
  • This method allows us to define what should happen once the promise resolves and data becomes available.

Advantages Over Callbacks

  • Unlike traditional callbacks where functions are passed blindly to APIs, promises allow us to attach callbacks directly to them, giving us more control over execution flow.
  • By attaching rather than passing functions, we ensure that our code executes only when the promise is fulfilled.

Guarantees Provided by Promises

  • Promises guarantee that once they resolve with data, they will call the attached callback function exactly once.
  • This eliminates concerns about multiple calls or missed executions common in callback patterns.

Exploring Real Promise Objects

  • The discussion transitions into examining real-world examples of promises using JavaScript's fetch API for making external calls.
  • The fetch function inherently returns a promise which can be captured in an object (e.g., user info from GitHub).

Understanding Promises in JavaScript

Exploring the Promise Object

  • The speaker adds a debugger to observe the state of a user object before executing a fetch function, which will return a promise.
  • Upon running the code, the promise object is displayed as an empty object, indicating that it has not yet resolved.
  • The promise contains properties such as promiseState and promiseResult, with the initial state being "pending" and result set to undefined.

States of a Promise

  • A promise can exist in one of three states: pending, fulfilled, or rejected. Initially, it starts in a pending state until data is returned from an asynchronous operation.
  • Once data is received (which may take several seconds), the promise transitions to a fulfilled state.

Logging Promise State

  • The speaker logs the user variable after calling fetch; at this point, it shows as pending because JavaScript does not wait for promises to resolve before executing subsequent lines.
  • When logged, the console displays "pending," but upon expansion reveals that it has transitioned to "fulfilled" once data arrives.

Handling Fulfilled Promises

  • After fulfillment, the promise's result property now contains response data including body and headers. This data can be processed further by converting readable streams into JSON format.
  • Callbacks can be attached to promises so that actions can be performed once data becomes available. This allows developers to handle results effectively.

Characteristics of Promises

  • Promises are immutable; once they are fulfilled or rejected, their state cannot change again. This immutability ensures reliability in handling asynchronous operations.

What is a Promise in JavaScript?

Understanding Promises

  • A promise allows developers to manage data without worrying about mutations, providing control over objects.
  • Promises are immutable and can be resolved only once, making them reliable for asynchronous operations.
  • When asked about promises in interviews, it's essential to articulate their definition clearly and confidently.

Definitions of Promises

  • One common definition describes a promise as a "placeholder" that will eventually hold a value from an asynchronous operation.
  • Another perspective views it as a "container for a future value," emphasizing its role in handling values that are not immediately available.
  • A more technical definition states that a promise is an object representing the eventual completion of an asynchronous operation.

Importance of Clear Definitions

  • The MDN definition highlights that promises represent the eventual completion of async operations, which is crucial for understanding their purpose.
  • Using precise definitions during interviews can prevent follow-up questions and demonstrate your knowledge effectively.

Callback Hell: The Challenges of Asynchronous Code

Issues with Callbacks

  • Callback hell arises when multiple dependent APIs lead to complex nested callbacks, making code difficult to read and maintain.
  • In e-commerce scenarios, sequential API calls (like creating orders and processing payments) illustrate how callback hell can occur due to dependencies between functions.

Visualizing Callback Hell

  • The sequence of operations—creating an order, proceeding to payment, showing order summary, and updating wallet balance—demonstrates the linear flow often seen in callback structures.
  • This structure leads to horizontal growth in code complexity rather than vertical clarity, resulting in what’s known as the "Pyramid of Doom."

Understanding Promise Chaining in JavaScript

The Problem with Callbacks

  • The speaker discusses the complexity and maintenance issues that arise when using callbacks, particularly in API interactions. This leads to "callback hell," making code difficult to read and manage.

Introduction to Promises

  • Promises are introduced as a solution to avoid callback hell. They allow for cleaner handling of asynchronous operations by enabling promise chaining.

Writing Promises

  • The speaker explains how to write promises effectively, demonstrating that attaching a callback function can be done directly after calling an API that returns a promise.

Implementing Promise Chaining

  • An example is provided where multiple .then() statements are used to handle sequential asynchronous operations, illustrating how additional callbacks can be added seamlessly in a chain.

Importance of Returning Promises

  • It’s emphasized that returning promises within each step of the chain is crucial for passing data correctly through the chain. Failing to do so can lead to bugs and unexpected behavior.

Arrow Functions vs Traditional Functions

  • The speaker notes that some developers prefer using arrow functions for their brevity and readability, although they express a personal preference for traditional function syntax.

Benefits of Using Promises

Cleaner Code Structure

  • By utilizing promise chaining, code becomes more organized and less cluttered compared to traditional callback methods, enhancing overall readability.

Trust and Immutability of Promises

What is a Promise in JavaScript?

Understanding Promises

  • A promise is an object that represents the eventual completion of an asynchronous operation. It serves as a placeholder for the result of that operation.
  • The definition to remember: "A promise is an object that represents the eventual completion of an async operation." Repeating this can help solidify understanding.

Callback Hell and Promise Chaining

  • Callback hell refers to the difficulties faced when using multiple nested callbacks, which can lead to complex and unreadable code.
  • Promise chaining allows developers to attach multiple callback handlers using .then(), making code cleaner and more manageable.
  • It's crucial to return promises within a chain; failing to do so may result in lost data during execution.

Creating Promises

  • Future discussions will focus on how to create custom promises, particularly through implementing APIs like createOrder.
  • The upcoming episode will explore how developers can generate trust in transactions by creating their own promises.

Homework Assignment

  • Viewers are encouraged to define what a promise means in their own words and explain its importance in comments.
  • This episode emphasizes the significance of understanding promises, urging viewers not only to watch but also engage with the content through homework questions.

Conclusion and Next Steps

  • The next video will delve into creating custom promises, building on the foundational knowledge established about consuming them.
Video description

Promises is the new way of handling asynchronous operations in JavaScript. This episode of Namaste JavaScript Season 2 will explain how Promises work in JavaScript along with code examples in detail. 00:00 - Introduction 00:50 - Code Example of Callbacks and Promises 08:05 - Promise.then function 09:30 - Callbacks vs Promises 11:23 - Importance of Promises 12:22 - Promise Object in Browser 15:58 - Deep dive into Promise States 21: 52 - Promise Interview Question 25:20 - Promise Chaining in JavaScript 30:13 - Common mistake while Promise Chaining 33:17 - Recap of the video 36:22 - Teaser of the Next Video 37:11 - Homework of this episode 38:32 - Thank you for watching Namaste JavaScript 🙏 If you find this video helpful, Please support me by giving a Super Thanks contribution to the video ♥️ If not by money, you can also support this video series, by sharing it with your friends on Social Media. 🙏 I'll give my best to come up with great content and everything absolutely for free on YouTube. 😊 Also, give it a thumbs up and subscribe to my channel for more such videos. 🔔 Link to Subscribe: https://www.youtube.com/c/akshaymarch7?sub_confirmation=1 Cheers, Akshay Saini http://akshaysaini.in Stay Connected: LinkedIn - https://www.linkedin.com/in/akshaymarch7 Facebook - https://www.facebook.com/akshaymarch7 Instagram - https://www.instagram.com/akshaymarch7 Twitter - https://twitter.com/akshaymarch7 #NamasteJavaScript #AkshaySaini