我有这种情况,我想知道承诺的状态。下面,函数start
仅在someTest
不再运行时调用start
(Promise未挂起)。可以多次调用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
我找不到简单检查承诺状态的方法。像awk '{sub(/_otherinfo/, "", $1); print "NEW_"$1 "\t" $2}' file
这样的东西会很好:)任何帮助都会受到赞赏!
答案 0 :(得分:18)
您可以附加then
处理程序,在承诺(或done
实例上设置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()
处理程序,无论promise的结果如何,都必须调用处理程序。
您可能希望将其包装在函数中以保持代码DRY。
答案 1 :(得分:1)
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);