代码之家  ›  专栏  ›  技术社区  ›  Lahiru Chandima

在不嵌套的情况下执行多个异步验证

  •  1
  • Lahiru Chandima  · 技术社区  · 8 年前

    我经常遇到这样的用例:在我完成一个任务之前,我必须进行几个异步验证。说, doValidationX() 返回一个承诺,如果验证成功则成功,否则失败。以下是我目前处理此类案件的方式。

    this.doValidation1(object).then(() => {
       this.doValidation2(object).then(() => {
           this.doValidation3(object).then(() => {
               this.doValidation4(object).then(() => {
                   this.doValidation5(object).then(() => {
                        //Do something.
                   }).catch(reason => console.log(reason));
               }).catch(reason => console.log(reason));
           }).catch(reason => console.log(reason));
       }).catch(reason => console.log(reason));
    }).catch(reason => console.log(reason));
    

    由于筑巢,它很难辨认。有没有一种方法可以避免嵌套并以更可读的方式组织此代码?我试着用 Promise.all() 但是很快意识到如果我这样做的话,所有的验证都会同时运行。我只想在第一次验证成功时运行第二次验证。

    2 回复  |  直到 8 年前
        1
  •  0
  •   Lahiru Chandima    8 年前

    比我想象的简单多了。感谢@jfriend00为我指明了正确的方向。

    this.doValidation1(object)
        .then(() => this.doValidation2(object))
        .then(() => this.doValidation3(object))
        .then(() => this.doValidation4(object))
        .then(() => this.doValidation5(object))
        .then(() => {
            //Do something
        }));
    
        2
  •  0
  •   Sergeon    8 年前

    实际上,这种方法可能不是最好的。你的验证似乎是 独立的 ,但您正在等待每个验证在下一个验证触发之前完成。这会导致不必要的空闲时间:如果验证需要1秒钟(例如),代码将运行5秒钟。如果您可以并行运行承诺(因此只等待一秒钟),则不需要这样做。

    One way to do so is to use Promise.all() ,它并行运行一系列承诺,并在所有承诺都成功解决时解析为true,否则拒绝:

    Promise.all([
      this.doValidation1(object),
      this.doValidation2(object),
      this.doValidation3(object),
      this.doValidation4(object),
      this.doValidation5(object),
    ]).then(() => {
      //validation passed
    }).catch((e) => {
      // validation failed.
    });
    

    然而,当承诺 不独立 (你需要第一个承诺在第二个承诺的结果,所以),你的方法是正确的。

    推荐文章