Jea*_*eri 39 javascript promise ecmascript-6 es6-promise
我有这种情况,我想知道一个承诺的状态.下面,该函数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
});
}
}
Run Code Online (Sandbox Code Playgroud)
我找不到简单检查承诺状态的方法.喜欢的东西this.promise.isPending会很好:)任何帮助将不胜感激!
Ami*_*mit 19
您可以附加一个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;
}
Run Code Online (Sandbox Code Playgroud)
注意空catch()处理程序,无论promise的结果如何,都必须调用处理程序.您可能希望将其包装在函数中以保持代码DRY.
| 归档时间: |
|
| 查看次数: |
43155 次 |
| 最近记录: |