DEV Community

Discussion on: Elegant way to check if a Promise is pending

Collapse
 
somedood profile image
Basti Ortiz • Edited

I mean this is cool and all, but I'm not really sure when one would ever want to know when a promise is "pending".

It's a fun experiment for the sake of learning, but usually, one would be better off just waiting until the Promise#then handler is fired.

However, if it is indeed "necessary" to do so (though I highly doubt that there is no better approach), you can use the Promise#then handler to achieve it more "elegantly" and concisely without the use of Node's meta tools.

let isPending = true;
Promise.resolve(1)
  .then(() => { isPending = false; });
Enter fullscreen mode Exit fullscreen mode
Collapse
 
devcrafter91 profile image
Drakos • Edited

If you're dealing with a scenario where you have a lot of promises and you wanted to just check the state for reporting or something, you must then define a bunch of variables for every promise which is ugly imho.

Collapse
 
somedood profile image
Basti Ortiz • Edited

In that case, assuming a Node environment as in your example in the article, wouldn't it be better (and more readable) to implement an event emitter instead?

It seems to me that promises may be the wrong abstraction for the job.

Collapse
 
callmelann profile image
CallMeLaNN

Checkout something like this, yeah, everything is just the Promise#then.

I never thought to check the "pending" even in a complex scenario. It is not something I wanted to grab and go, I'll come back later. Maybe you need it if you deal with coroutine or infinite loop but JS don't need that and I never done that on function generator too since there are always a way:

Since we can keep promise instance around, we can always append more or chain Promise#then to structure the flow we want.

Collapse
 
jakobrosenberg profile image
Jakob Rosenberg

Promise.all is great if you're working with a static array, but what if your array is dynamic? Promises added between the wait and the resolve will then be ignored.

To solve that you could do something like

/**
 * @param {Promise<any>[]} promises
 */
const dynamicPromiseAll = async (promises) => {
  const result = await Promise.all(promises);
  const hasPending = promises.map((promise) => util.inspect(promise).includes("pending")).filter(Boolean).length;
  return hasPending ? dynamicPromiseAll(promises) : result;
};
Enter fullscreen mode Exit fullscreen mode