在这种情况下,我想知道承诺的地位。在下面,该函数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
处理程序,该处理程序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] 删除。
我来说两句