JS Promise

Introduction

In JavaScript, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It helps manage asynchronous operations more effectively than traditional callback functions.

Need for JavaScript Promises

Promises address some of the limitations of callbacks and events in managing asynchronous operations. Unlike callbacks, Promises offer a more structured approach to handling asynchronous code and avoid common issues such as callback hell.

Key Terminology

Pending: The initial state of a promise. The promise is neither fulfilled nor rejected.

Fulfilled: The state when the asynchronous operation completes successfully.

Rejected: The state when the asynchronous operation fails.

Settled: The state when the promise has either been fulfilled or rejected.

Promise Characteristics

1. Single Completion: A Promise can only succeed or fail once.

2. Immutability: Once a Promise is fulfilled or rejected, it cannot change its state.

Promise Methods

1. Promise.resolve(value):

Returns a Promise that is resolved with the given value.

If the value is already a Promise, it returns that Promise.

2. Promise.reject(reason):

Returns a Promise that is rejected with the given reason.

3. Promise.all(iterable):

Returns a Promise that resolves when all Promises in the iterable argument have resolved, or rejects with the reason of the first promise that rejects.

4. Promise.race(iterable):

Returns a Promise that resolves or rejects as soon as one of the Promises in the iterable resolves or rejects, with the value or reason from that Promise.

5. Promise.any(iterable):

Returns a Promise that resolves when any of the Promises in the iterable resolves, or rejects if no Promise in the iterable resolves.

Promise.finally(onFinally):

Adds a handler to be called when the Promise is settled, regardless of its outcome.

Constructor

new Promise(function(resolve, reject) {
// Asynchronous code here
if (/* operation successful */) {
resolve(result); // Resolves the promise with the result
} else {
reject(error); // Rejects the promise with the error
}
});

resolve(value): The function to call when the operation completes successfully.

reject(reason): The function to call when the operation fails.

Advantages of Using Promises

1. Improved Readability: Promises avoid nested callbacks and improve code readability.

2. Better Error Handling: Promises provide a clear and consistent way to handle errors with .catch().

Example:

<script>
    var p = new Promise(function(resolve, reject) {
        var x = 5;
        if (x == 4)
            resolve(" executed and resolved successfully");
        else
            reject("rejected");
    });
    p.then(function(fromResolve) {
        document.write("Promise is " + fromResolve);
    }).catch(function(fromReject) {
        document.write("Promise is " + fromReject);
    });
</script>

Output:

Promise is rejected