Sam R.
Sam R.

Reputation: 16450

AngularJS reject a promise in success callback

I'm using $q to check if two resources' queries have been resolved or not. 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. 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?

Upvotes: 2

Views: 1110

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

This is actually simpler than the comment suggests since promises chain. If you want to chain though - you need to do it with 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");
});

Upvotes: 4

Related Questions