如何检查Promise是否处于挂起状态
How to check if a Promise is pending
在这种情况下,我想知道承诺的状态。下面,函数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);
相关文章:
- JavaScript执行暂时挂起页面
- 是定义的操作系统睡眠/挂起期间setTimeout的行为
- Chrome浏览器“;挂起”;同时在循环中执行AJAX请求
- 我如何为列出的选项卡元素编写一个Protractor测试,它会检查它是否's是否处于活动状态
- fullcalendar在删除导致浏览器挂起的多个事件时速度较慢
- 应用将图表转换为图像的jqplot代码时Chrome挂起
- 如何在不使用Internet Explorer的情况下从未挂起的HTML文件执行程序
- MongoDB collection.find()查询挂起
- 使用子字符串方法时应用程序挂起的原因
- 如何查明SignalR客户端上是否有挂起的请求
- JS调试器是否挂起整个JS事件循环
- React计时器挂起:00(状态未更新)
- 如何检查Promise是否处于挂起状态
- Javascript-承诺保留为挂起状态
- WinJS 句柄挂起状态
- AngularJS后续$http删除将保持挂起状态几分钟
- 是否有可能在单击复选框时停止更改,挂起某些复选框
- 在Windows 8 html5的挂起状态事件处理程序中写入文本文件
- 有没有办法知道链接/脚本是否仍然挂起或失败
- 如何调试后台/事件页面挂起状态