How to check if a Promise is pending [duplicate]

You can attach a then handler that sets a done flag on the promise (or the RunTest instance if you prefer), and test that:

     if (!this.promise) {
         this.promise = this.someTest();
         this.promise.catch(() => {}).then(() => { this.promise.done = true; });
         retVal = true;                
     }

     if ( this.promise.done ) {
         this.promise = this.someTest();
         this.promise.catch(() => {}).then(() => { this.promise.done = true; });
         retVal = true;
     }

Notice the empty catch() handler, it's crucial in order to have the handler called regardless of the outcome of the promise. You probably want to wrap that in a function though to keep the code DRY.


class RunTest {
   constructor() {
    this.isRunning = false;
   }
   start() {
      console.log('isrunning', this.isRunning);
      var retVal = false;
      if(!this.isRunning) {
        this.promise = this.someTest();
        this.promise.catch().then(() => { this.isRunning = false; });
        retVal = true;                
      }
      return retVal;
    }
    someTest() {
        this.isRunning = true;
        return new Promise((resolve, reject) => {
          setTimeout(function() {
             //some tests go inhere
             resolve();
           }, 1000);
        });
    }
};

var x = new RunTest();

x.start(); //logs false
x.start(); //logs true

setTimeout(function() {
    //wait for a bit
  x.start(); //logs false
}, 2000);