【问题标题】:AngularJS conditional case for .then based on var value known only before the first .then.then 的 AngularJS 条件案例基于仅在第一个 .then 之前已知的 var 值
【发布时间】:2017-06-16 19:27:10
【问题描述】:
我有一个运行良好的代码:
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(为真)还是执行另一个.then INSTEAD(为假) .
angularJS的方式怎么实现?
谢谢。
【问题讨论】:
标签:
javascript
angularjs
promise
conditional
angular-promise
【解决方案1】:
我认为你必须在每个回调中检查 ``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
});
或者您可以嵌套承诺,这样您就不必一直检查值。但老实说,我更喜欢重复检查而不是嵌套承诺。