【问题标题】:Function only after all asynchronous callbacks are completed in if statements仅在 if 语句中完成所有异步回调后才起作用
【发布时间】:2018-03-09 21:38:32
【问题描述】:

我想在异步函数的所有回调完成后关闭某个页面,但并非所有if() 语句都可能为真。现在它看起来像这样:

if (this.originalFrom > addFrom) {
      this.dataService.addTimeSlots(details).then((result) => {
        console.log(result);
      }, (err) => {
        console.log(err);
      });
    }
if (this.originalTo < addTo) {
      this.dataService.addTimeSlots(details2).then((result) => {
        console.log(result);
      }, (err) => {
        console.log(err);
      });
    }
if (this.originalTo > addTo) {
      this.dataService.addTimeSlots(details3).then((result) => {
        console.log(result);
      }, (err) => {
        console.log(err);
      });
    }
some_Page_Closing_Function_When_All_Callbacks_Are_Done();

【问题讨论】:

    标签: javascript typescript asynchronous


    【解决方案1】:

    您要做的是在所有回调完成后调用该函数。如果一个 if 语句返回 false,那么你要抓住整个过程。

    这样做的一种较差的方法是以这种格式嵌套回调:

      1 if (this.originalFrom > addFrom) {
      2     this.dataService.addTimeSlots(details).then((result) => {
      3         console.log(result);
      4         if (this.originalTo < addTo) {
      5             this.dataService.addTimeSlots(details2).then((result) => {
      6                 console.log(result);
      7                 if (this.originalTo > addTo) {
      8                     this.dataService.addTimeSlots(details3).then((result) => {
      9                         console.log(result);
     10                         some_Page_Closing_Function_When_All_Callbacks_Are_Done();
     11                     }, (err) => {
     12                         console.log(err);
     13                     });
     14                 }
     15             }, (err) => {
     16                 console.log(err);
     17             });
     18         }
     19
     20     }, (err) => {
     21         console.log(err);
     22     });
     23 }
    

    但是,这被称为回调地狱。冗长、不可读、不可维护的意大利面条代码。

    您可以尝试将匿名函数转换为命名函数以获得更易读的解决方案。这仍然有点老套。

    https://github.com/caolan/async

    https://caolan.github.io/async/

    您可以使用这个库来避免上述回调地狱。

    【讨论】:

      【解决方案2】:

      你可以使用Promise.all

      var promises = [];
      
      if (this.originalFrom > addFrom) {
          promises.push(this.dataService.addTimeSlots(details));
      }
      
      if (this.originalTo < addTo) {
          promises.push(this.dataService.addTimeSlots(details2));
      } else if (this.originalTo > addTo) {
          promises.push(this.dataService.addTimeSlots(details3));
      }
      
      Promise.all(promises).then((result) => {
          console.log(result);
      }, (err) => {
          console.log(err);
      });
      

      【讨论】:

      • 其实我更喜欢这个答案。
      猜你喜欢
      • 2013-09-29
      • 2019-11-13
      • 2018-03-30
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 2023-01-08
      • 1970-01-01
      相关资源
      最近更新 更多