我有一个工作正常的代码:

    myService.myFunc1()
        .then(myService.myFunc1)
        .then(function(dataA) {
            // do something
        })
        .then(myService.myFunc2)
        .then(function(dataB) {
            //do something
        });


但是,在执行myFunc1时,布尔值myService.trig的值已正确设置。我想更改上面的代码以使其基于myService.trig布尔值有条件,并决定是在myService.myFunc1().之后执行其余的所有.then(对于true)还是对彼此执行.then INSTEAD(对于false) 。

如何以angularJS方式完成?

谢谢。

最佳答案

我认为您将必须在每个回调中检查``myService.trig''的值是什么。

myService.myFunc1()
     .then(() => {
         // execute this function if the "myService.trig" is true
         if (!myService.trig) return;
         return myService.myFunc1;
     })
     .then((dataA) => {
         // execute this function if the "myService.trig" is true
         if (!myService.trig) return;
         // do something
     })
     .then(() => {
         // execute this function if the "myService.trig" is false
         if (myService.trig) return;
         return myService.myFunc2;
     })
     .then((dataB) =>  {
         // execute this function if the "myService.trig" is false
         if (myService.trig) return;
         // do something
     });


或者,您可以嵌套诺言,这样您就不必一直检查价值。但是老实说,我宁愿重复检查而不是嵌套承诺。

07-24 17:55
查看更多