loading...

Elegant way to check if a Promise is pending

devcrafter91 profile image Mak 🇪🇺 ・1 min read

Intro

There's no solid way to check if a Promise is pending or finished, at least not in Node.js, so I wrote this simple snippet back in few months ago while I was searching for a simple way. I couldn't' find anything with one line max that will check the state of a promise so I came up with this simple solution. I have posted this solution on StackOverflow too. It's nothing special just an elegant & hacky way but works flawlessly on every Node.js version from 8~14. It's not stable though and the rational solution here should be a native method inside V8's core to check if a promise is pending or not.

The trick

If we take the whole object of a promise and inspect it using the inspect method from the native libraries of Node.js, we will get either 'Promise { <pending> }' while pending or 'Promise { undefined }' when finished.
Now if we check the string for the word pending we could define the state and check if a promise is pending or not using the following one line: util.inspect(myPromise).includes("pending").

Here's an example to get you started:

const util = require("util")

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

(async ()=>{
  let letmesleep = sleep(13000)
  setInterval(()=>{
    console.log(util.inspect(letmesleep).includes("pending"))
  },1000)
})()

Result

true
true
false
false
false

Posted on by:

devcrafter91 profile

Mak 🇪🇺

@devcrafter91

Messing up with Linux servers, AWS, Node.js, Angular and sometimes Kotlin (Android) . Follow me on Twitter! (fresh blood) https://mobile.twitter.com/devcrafter91

Discussion

markdown guide
 

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; });
 

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.

 

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.