如何对两个返回promise的函数的运行进行排序?

时间:2016-06-21 10:27:33

标签: javascript typescript

我的代码检查word.statusId以查看它是否脏。如果是,那么它会更新单词然后如果有效则更新wordForms。如果它是干净的,那么它只是更新wordForms。有人可以告诉我,如果这是处理一个接一个的承诺的正确方法吗?

update = (): ng.IPromise<any> => {
        var self = this;
        if (self.word.statusId != 3) {
            return self.wordEditSubmit()
                .then(() => {
                    return self.wordFormCheckAndUpdate();
                })
        } else {
            return self.wordFormCheckAndUpdate();
        }
    }

1 个答案:

答案 0 :(得分:4)

您所描述的所需行为确实是实际行为。

当您使用arrow functions时,您无需存储this的值:

update = (): ng.IPromise<any> => {
  if (this.word.statusId != 3) {
    return this.wordEditSubmit()
      .then(() => this.wordFormCheckAndUpdate())
  } else {
    return this.wordFormCheckAndUpdate();
  }
}

使用ternary condition再次简化:

update = (): ng.IPromise<any> => {
  return this.word.statusId != 3
    ? this.wordEditSubmit().then(() => this.wordFormCheckAndUpdate())
    : this.wordFormCheckAndUpdate();
}