ππ«π¨π¦π’π¬π.π°π’ππ‘πππ¬π¨π₯π―ππ«π¬ β π πππ° πππ² ππ¨ ππ«ππππ ππ«π¨π¦π’π¬ππ¬ in πππ―ππππ«π’π©π
The traditional way to create a promise is using the ππ«π¨π¦π’π¬π constructor.
There is a new feature in JavaScript called ππ«π¨π¦π’π¬π.π°π’ππ‘πππ¬π¨π₯π―ππ«π¬.
Promise.withResolvers is a function that returns an object with two properties: a promise and a set of resolve and reject functions. This allows us to create a promise and manage its resolution or rejection in a more streamlined way.
In the example below, we use Promise.withResolvers creates an object with a promise and two functions resolve and reject. The asynchronous operation is simulated using setTimeout, and the appropriate function (resolve or reject) is called based on the outcome.
// Promise.withResolvers()
const { promise, resolve, reject } = Promise.withResolvers();
// Perform some async operation
setTimeout(() => {
resolve('Data fetched successfully!');
}, 1000);
promise
.then((data) => {
alert(data); // Output: 'Data fetched successfully!'
})
.catch((error) => {
alert(error);
});
I hope you found it useful. Thanks for reading. π
Letβs get connected! You can find me on:
Hashnode: https://nhannguyen.hashnode.dev/
X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs