我如何实现递归承诺?

时间:2016-09-22 12:55:19

标签: javascript promise es6-promise

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

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)});

我希望一次调用>= 4resolve就可以触发上述&#34;然后&#34;。

2 个答案:

答案 0 :(得分:3)

你需要用新的承诺解决内部承诺,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());解决新的递归承诺。

查看下面的演示。

&#13;
&#13;
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}`));
&#13;
&#13;
&#13;

答案 1 :(得分: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");
            }
        });
    }