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
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
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()
:
const { promise, resolve, reject } = Promise.withResolvers();
Example: Waiting for a Button Click with Cancel Option using Promise.withResolvers()
<!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()
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
WithPromise.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?
Happy Coding !!
Top comments (0)