DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

๐๐ซ๐จ๐ฆ๐ข๐ฌ๐ž.๐ฐ๐ข๐ญ๐ก๐‘๐ž๐ฌ๐จ๐ฅ๐ฏ๐ž๐ซ๐ฌ - ๐€ ๐๐ž๐ฐ ๐–๐š๐ฒ ๐ญ๐จ ๐‚๐ซ๐ž๐š๐ญ๐ž ๐๐ซ๐จ๐ฆ๐ข๐ฌ๐ž๐ฌ 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);
  });
Enter fullscreen mode Exit fullscreen mode

I hope you found it useful. Thanks for reading. ๐Ÿ™

Let's get connected! You can find me on:

Top comments (2)

Collapse
 
darkwiiplayer profile image
๐’ŽWii ๐Ÿณ๏ธโ€โšง๏ธ

That's a really neat helper. I often find myself implementing basically the same thing (although I usually just end up putting the accept and reject functions in the promise so I can call them as methods).

Collapse
 
artydev profile image
artydev

Thank you :-)