New Feature in ECMAScript 2024 - Promise.withResolvers()
Tags: javascript, webdev, programming, es15
Published: 2024-07-06 07:40:14


### Promise.withResolvers()
####Regular Promise
A JavaScript Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.

We create a Promise using the Promise constructor, which takes a function (executor) with two arguments: resolve and reject. Below is the boilerplate code

```javascript
const promise = new Promise((resolve, reject) => {
    // Asynchronous operation
    if (/* operation is successful */) {
        resolve('Success!');
    } else {
        reject('Failure.');
    }
});

promise
    .then(result => console.log(result))
    .catch(error => console.error(error));

```
Check the example in codepen [Regular Promises](https://codepen.io/Raju-Saha-the-decoder/pen/bGPbZLZ?editors=1011)

###Introducing `Promise.withResolvers()`
The `Promise.withResolvers()` method simplifies the creation of promises by returning an object containing a new promise along with its resolve and reject functions. This avoids the need for additional boilerplate code and makes the promise handling more concise.

Here's the syntax for using `Promise.withResolvers()`:

```javascript
const { promise, resolve, reject } = Promise.withResolvers();
```
Example: Waiting for a Button Click with Cancel Option using `Promise.withResolvers()`

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise.withResolvers() Example</title>
</head>
<body>
    <button id="myButton">Click me</button>
    <button id="cancelButton">Cancel</button>

    <script>
        function waitForButtonClick(buttonId, cancelButtonId) {
            const { promise, resolve, reject } = Promise.withResolvers();
            const button = document.getElementById(buttonId);
            const cancelButton = document.getElementById(cancelButtonId);

            button.addEventListener('click', () => resolve('Button clicked!'));
            cancelButton.addEventListener('click', () => reject('Action cancelled!'));

            return promise;
        }

        async function main() {
            try {
                console.log('Waiting for button click or cancellation...');
                const result = await waitForButtonClick('myButton', 'cancelButton');
                console.log(result);
            } catch (error) {
                console.error(error);
            }
        }

        main();
    </script>
</body>
</html>

```
CodePen for the above example [Promise with Promise.withResolvers()](https://codepen.io/Raju-Saha-the-decoder/pen/PorYLex?editors=0011)

####Key Differences and Benefits

- **Conciseness**
`Promise.withResolvers()` reduces boilerplate code by directly providing the resolve and reject functions along with the promise object. This can make the code cleaner and easier to read.

- **Scope Management**
With `Promise.withResolvers()`, the resolve and reject functions are within the same scope as the promise itself, which can simplify the logic for resolving or rejecting the promise based on asynchronous events.

- **Use Case Flexibility**
`Promise.withResolvers()` is particularly useful in scenarios where the resolution or rejection needs to happen outside of the initial executor function, such as event listeners, timeouts, or other asynchronous callbacks.

###Conclusion
Both JavaScript `promises `and `Promise.withResolvers()` are powerful tools for managing asynchronous operations. While traditional `promises `provide robust functionality, `Promise.withResolvers()` offers a more concise and convenient way to handle promises, especially in complex asynchronous workflows.

Checkout next Post for other features

Reference [Ecma International approves ECMAScript 2024: What’s new?](https://2ality.com/2024/06/ecmascript-2024.html#promise.withresolvers())

Happy Coding !!