gpt4 book ai didi

angularjs - 在 Angularjs 中打破 promise

转载 作者:行者123 更新时间:2023-12-01 09:30:27 26 4
gpt4 key购买 nike

我正在尝试找到一种方法来打破 AngularJS 代码中的 promise 链。显而易见的方法是返回一个对象,然后检查链中每个“then”函数的有效性。

我想找到一种更优雅的方式来打破当时的链条。

最佳答案

在 Angular 中,有可以注入(inject)指令、 Controller 等的 $q 服务,这是对 Kris Kowal 的 Q 的紧密实现。所以在 then 函数内部而不是返回一个值或其他将链接到下一个“thenable”函数的东西,只需返回一个 $q.reject('reject reason');

例子:

angular.module('myQmodule',[])
.controller('exController',['$q',function($q){
//here we suppose that we have a promise-like function promiseFunction()
promiseFunction().then(function(result1){
//do the check we want in order to end chain
if (endChainCheck) {
return $q.reject('give a reason');
}
return;
})
.then(function(){
//this will never be entered if we return the rejected $q
})
.catch(function(error){
//this will be entered if we returned the rejected $q with error = 'give a reason'
});
}]);

关于angularjs - 在 Angularjs 中打破 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26781152/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com