Promise.withResolvers in JavaScript
Let me know if you've heard this one before. You have a function that is reading some sort of file (let's say a csv with a known format and no header line). You want to use streams so you can act on each line but you need to return a promise that resolves once the file has been fully read. Nine times out of ten, you've probably been wrapping the whole function up in a promise definition. I'd suspect something like the below code.
Perhaps, you try to be a bit cleaner with your code and have instead been pulling the resolve and reject methods out of the promise to avoid unnecessary indentation. A worthy goal to make the code "cleaner" but at the cost of adding a bit of additional boilerplate to the start of your function.
Enter Promise.withResolvers
As of this month (March 2024) you actually have a new option, using Promise.withResolvers, which returns an object containing a new promise as well as the resolve and reject methods. This means that with a bit of destructuring, you can pull out your resolvers in a single clean line.
It's already supported in all major browsers as well as in NodeJS behind a feature flag. As of Node v21.7.1, using node --js-promise-withresolvers index.js will enable the flag for your script. That being said, I'd imagine NodeJS will support it fully within a short period of time.
Let's take another look at our CSV reading example. This time though, we'll use the withResolvers method rather than manually pulling out the resolvers ourselves.
Some Other Example Use Cases
A regular use case for manually creating promises is for an awaitable wait function. Despite both versions of this code taking up 5 lines, I think you'll agree with me that the withResolvers version is much quicker to parse mentally.
Because you can pass around the resolvers from Promise.withResolvers, it allows you to do some interesting things in reactive frameworks like Svelte or React. The following code uses the resolve and reject methods to log out a message only after a button has been pressed by abusing standard .then and .catch handlers.
Conclusion
I'm really excited to see all the ways this simple addition to promises impacts our coding practices. If you end up using Promise.withResolvers for anything interesting, please leave me a comment over on Github or Bluesky to tell me about it.
Webmentions
What's this?This site uses Webmentions to handle likes, comments and other interactions. To leave a comment, you can reply on GitHub, Reddit, or Bluesky. While the site will count likes from any source, only Bluesky likes are currently displayed in the facepile.