简体   繁体   English

AngularJS拒绝成功回调中的承诺

[英]AngularJS reject a promise in success callback

I'm using $q to check if two resources' queries have been resolved or not. 我正在使用$q检查两个资源的查询是否已解决。 Like this: 像这样:

$q.all([
    ResourceA.get({}, function success(data) {
        console.log("got A");
    }).$promise,
    ResourceB.get({}, function success(data) {
        console.log('got B');
    }).$promise
]).then(function() {
    console.log("done");
});

The question is, the data I'm receiving in each of the success functions might not be what I want and I wanna check if that's the case then reject the correspondent promise. 问题是,我在每个success函数中接收的data可能不是我想要的,我想检查是否是这种情况,然后拒绝相应的承诺。 Like: 喜欢:

$q.all([
    ResourceA.get({}, function success(data) {
        if (data.key !== "secret") {
            // REJECT THE PROMISE
        }
    }).$promise,
    ResourceB.get({}, function success(data) {
        console.log('got B');
    }).$promise
]).then(function() {
    console.log("done");
});

Is this possible? 这可能吗? How? 怎么样? Any better way? 还有更好的方法吗?

This is actually simpler than the comment suggests since promises chain. 这实际上比承诺承诺链中的评论要简单。 If you want to chain though - you need to do it with then : 如果你想链,但-你需要做的then

$q.all([
    ResourceA.get({}).$promise.then(function(data){ // chain a then
        if (data.key !== "secret") return $q.reject("Invalid key");
        return data; // return same value if ok
    }),
    ResourceB.get({}, function success(data) {
        console.log('got B');
    }).$promise
]).then(function() {
    console.log("done");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM