【问题标题】:How do I implement recursive promises?如何实现递归承诺?
【发布时间】:2017-01-31 01:40:37
【问题描述】:

我写了一个重试机制,应该返回一个承诺:

private connect(): Promise<any> {
      return new Promise((resolve, reject) => {
          if(this.count < 4) {
             console.log("count < 4, count:"+this.count);
             this.count++;
             return this.connect();
            } else {
              resolve("YES");
            }
        });
    }

如果我打电话:

t.connect().then((data:any)=>{ console.log("YES:"+data)});

我希望调用一次计数&gt;= 4resolve 能够触发上述“then”。

【问题讨论】:

  • "我想一次 count >= 4 并调用 resolve 来触发上面的 "then"" - 尝试改写这句话。
  • Here 您可以找到详细的承诺工作流程,其中包含几个顺序链接的承诺,每个承诺在拒绝之前尝试 5 次。通过递归计数传递实现。

标签: javascript promise es6-promise


【解决方案1】:

尝试将计数传递给连接

private connect(count = 0): Promise<any> {
      return new Promise((resolve, reject) => {
          if(count  < 4) {
             console.log("count < 4, count:"+count);
             return this.connect(++count);
            } else {
              resolve("YES");
            }
        });
    }

【讨论】:

  • 更好:以count = 4开头,count &gt; 0递减,这样可以改变重试次数
  • 无需传递计数,OP 似乎将count 属性定义为t 对象的一部分。无论如何,这也行不通。
  • 啊,是的,承诺没有解决。 @dfsq 的解决方案将起作用,但您需要确保重置 this.count 否则每次都会得到解决(除非这是您需要的行为)。
【解决方案2】:

你需要用新的promise解决内部promise,return this.connect()是不够的:

function connect(): Promise<any> {
  return new Promise((resolve, reject) => {
    if (this.count < 4) {
      console.log("count < 4, count:" + this.count);
      this.count++;
      resolve(this.connect());
    } else {
      resolve("YES");
    }
  });
}

注意,您如何使用 resolve(this.connect()); 解决新的递归承诺。

查看下面的演示。

function connect() {
  return new Promise((resolve, reject) => {
    if (this.count < 4) {
      console.log("count < 4, count:" + this.count);
      this.count++;
      resolve(this.connect());
    } else {
      resolve("YES");
    }
  });
}

const t = {count: 0, connect}

t.connect().then(data => console.log(`YES: ${data}`));

【讨论】:

  • 为什么不使用reject?这个问题是否有特定的原因或含糊不清?如果没有理由 - 我很想知道该怎么做 =)
猜你喜欢
  • 2014-02-04
  • 1970-01-01
  • 2016-12-02
  • 2016-12-23
  • 2017-03-26
  • 1970-01-01
  • 2018-05-29
  • 2017-11-01
  • 1970-01-01
相关资源
最近更新 更多