如何检查Promise是否未决

Jeanluca Scaleri:

在这种情况下,我想知道承诺的地位。在下面,该函数startsomeTest在不再运行时才调用(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处理程序,处理程序done在promise(或RunTest您希望实例)设置标志,并进行测试:

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

请注意,空catch()处理程序非常重要,以便无论承诺的结果如何,都必须调用该处理程序。您可能希望将其包装在函数中,以保持代码DRY。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章