如何检查Promise是否处于挂起状态

How to check if a Promise is pending

本文关键字:是否 挂起状态 Promise 何检查 检查      更新时间:2023-09-26

在这种情况下,我想知道承诺的状态。下面,函数start仅在不再运行时调用someTest(Promise未挂起)。start函数可以被调用多次,但如果它在测试仍在运行时被调用,它就不会等待,只返回false

class RunTest {
    start() {
         retVal = false;
         if (!this.promise) {
             this.promise = this.someTest();
             retVal = true;                
         }
         if ( /* if promise is resolved/rejected or not pending */ ) {
             this.promise = this.someTest();
             retVal = true;
         }
         return retVal;
    }
    someTest() {
        return new Promise((resolve, reject) => {
            // some tests go inhere
        });
    }
}

我找不到简单地检查承诺状态的方法。类似this.promise.isPending的东西会很好:)任何帮助都将不胜感激!

您可以附加一个then处理程序,该处理程序在promise(或者RunTest实例,如果您愿意的话)上设置done标志,并测试它:

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

finally()处理程序确保不管promise的结果如何都设置done标志。

不过,您可能希望将其封装在一个函数中,以保持代码干燥。

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