DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

4

𝐏𝐫𝐨𝐦𝐢𝐬𝐞.𝐰𝐢𝐭𝐡𝐑𝐞𝐬𝐨𝐥𝐯𝐞𝐫𝐬 - 𝐀 𝐍𝐞𝐰 𝐖𝐚𝐲 𝐭𝐨 𝐂𝐫𝐞𝐚𝐭𝐞 𝐏𝐫𝐨𝐦𝐢𝐬𝐞𝐬 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:

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

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 :-)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay