承诺链中的递归函数

时间:2017-04-03 17:24:50

标签: angular typescript promise

我想多次触发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;
}

1 个答案:

答案 0 :(得分:0)

setTimeout不会返回一个promise,而您作为回调传递的“递归调用”的结果将被忽略。所以宣布超时:

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