Javascript 如何检查承诺是否待定

Javascript 如何检查承诺是否待定,javascript,promise,ecmascript-6,es6-promise,Javascript,Promise,Ecmascript 6,Es6 Promise,在这种情况下,我想知道承诺的状态是什么。下面,函数start仅在不再运行时调用someTest(Promise未挂起)。可以多次调用start函数,但如果在测试仍在运行时调用它,它将不会等待,只返回false class RunTest { start() { retVal = false; if (!this.promise) { this.promise = this.someTest(); r

在这种情况下,我想知道承诺的状态是什么。下面,函数
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
        });
    }
}

我找不到一种简单地检查承诺状态的方法。类似于
的东西。promise.isPending
会很好:)任何帮助都将不胜感激

您可以附加一个
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()
处理程序,无论承诺的结果如何,都必须调用该处理程序。
不过,您可能希望将其包装在函数中以保持代码干燥。

用例是什么?我不认为原生承诺支持这一点,这是一件奇怪的事情,但Blubird不确定您是否已经检查过Mozilla,但他们有很好的例子和承诺文档-在我的例子中,它是一个
setInterval
始终调用异步的东西。某个东西一次只能运行一个。我当然可以在
this
上设置一个变量,比如
this.isBusy=true
。但在我看来,这听起来像是一种不知道承诺状态的变通方法mozilla页面确实很棒,但是没有关于如何检查承诺状态的内容。如果我错过了,请告诉我!检查承诺是否挂起似乎并不“奇怪”,它似乎是绝对基本的。在
then()
之后返回承诺有一个缺点-您不能将已解析的值传递给下一个处理程序。另外,如果测试抛出(请参阅我的答案),这将不起作用。
then
回调我想只执行
this.promise=null
一个“empty”
catch
参数不起作用。您仍然需要显式地传递一个空函数,否则它就没有意义了。@Bergi-关于空捕获的好观点,现在更正。。。关于
this.promise=null
,在这种特定情况下是可以的,但一般来说没有那么健壮。例如,如果在函数外公开了承诺的属性,那么在承诺上提供属性就更好了。当然,但是通常没有人希望在承诺上使用这样的属性,所以没有必要公开它。在您认为需要确定承诺状态的所有情况下,您实际需要的是检查您的回调是否已被调用。FWIW,替换
.catch(()=>{})。然后可以考虑使用()。
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);