【问题标题】:Recursive function in promises chain承诺链中的递归函数
【发布时间】:2017-04-04 03:14:34
【问题描述】:

我想多次触发 promise 函数,直到服务器返回适当的请求状态。我将此函数称为“checkStatus”。我不知道如何实现这一点。

saveFile() {
  this.createMetadataContainer(this.fileId).then((data) => {
    this.metadataInfo = data;
    return this.createResourceMember(data, this.fileId, this.code);
  }).then((data) => {
    this.metadataInfo = data;
    return this.applyCodeChanges(data);
  }).then((data) => {
    return this.checkStatus(data.id, this.metadataInfo);
  }).catch((err) => {
    this.deleteMetadataContainer(this.metadataInfo);
  }).then((data) => {
    this.msg = 'Code Saved';
  });

}

这就是我编写 checkStatus 函数的方式:

checkStatus(id, metadataInfo) {
  let promise = this.server.retrieve('ContainerAsyncRequest', id).then((data) => {
    if(data.State == "Completed") {
      return data;
    }else if(data.State == "Queued") {
      this.msg = 'Saving Code...';
      return setTimeout(this.checkStatus(id, metadataInfo), 2000);
    }else {
      this.msg = 'Compiler Error ' + data.CompilerErrors;
      return data;
    }
  });
  return promise;
}

【问题讨论】:

    标签: angular typescript promise


    【解决方案1】:

    setTimeout 不返回承诺,您作为回调传递的“递归调用”的结果将被忽略。所以承诺超时:

    function wait(t) {
        return new Promise(resolve => {
            setTimeout(resolve, t);
        });
    }
    

    并在链中使用它:

    checkStatus(id, metadataInfo) {
      return this.server.retrieve('ContainerAsyncRequest', id).then(data => {
        if (data.State == "Completed") {
          return data;
        } else if (data.State == "Queued") {
          this.msg = 'Saving Code...';
          return wait(2000).then(() =>
            this.checkStatus(id, metadataInfo)
          );
        } else {
          this.msg = 'Compiler Error ' + data.CompilerErrors;
          return data;
        }
      });
    }
    

    【讨论】:

    • 谢谢,它正在工作。我正在学习 Promises,你帮了我很多。
    猜你喜欢
    • 1970-01-01
    • 2018-12-01
    • 2017-12-18
    • 2019-05-25
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 2014-06-30
    相关资源
    最近更新 更多