Promises in Javascript

luhan
انضم:
2024-07-16 06:08:00

This thread will be talking about `promises` and this is a continuation of the async functions post. Click on this link "https://afr.ng/8cf2385e" if you haven't read the async/await post.

So JavaScript is all about keeping things moving, but sometimes you have got to wait for something to finish. Promises are here to ensure you don't get stuck in code limbo!

**What are Promises?**

Promises are objects that represent the eventual completion (or failure) of an asynchronous operation. They act like a placeholder, saying "Hey, I'll get you the result when it's done."

**Think of it like an order:** Imagine you order a pizza. You don't get it right away, but the restaurant gives you a receipt (the promise) saying they'll deliver it eventually. The receipt tells you it'll be delicious (resolved promise) or burnt (rejected promise).

Image preview

luhan
انضم:
2024-07-16 06:14:21

**Key points about Promises:**

  • *

    **States of a Promise:** A promise can be in three states: pending (waiting), fulfilled (finished successfully), or rejected (failed).

  • *

    **Waiting with `then`:** You can use the `then` method to specify what to do with the result (like eating your pizza) once the promise is fulfilled.

  • *

    **Handling Errors with `catch`:** The `catch` method allows you to handle any errors (like a burnt pizza) that might occur during the asynchronous operation.

  • I prefer the `try…catch` where you wait for your line of code with `async/await` method more than traditional `.then`.

    Interestingly, react also provides the Promise.all(), Promise.resolve(), and Promise.reject() method and this is why I enjoy writing code because there are always new/exciting things to learn

    Simplythebest
    انضم:
    2024-07-21 01:49:17

    I am yet to master the promise.all()

    jenny
    انضم: 2025-08-24 15:11:06
    2024-07-21 01:51:39

    This is one of the areas that you must master as a javascript engineer especially when communicating with external APIs.

    luhan
    انضم:
    2024-07-21 08:40:56

    @"Simplythebest"#p1004`promise.all `always returns a single promise. Either a fulfilled promise or a rejected one. It's almost like `promise.fulfill` and `promise.reject` except that you give it more than one argument.

    Facebook X (Twitter) Instagram LinkedIn Telegram WhatsApp