yayitswei
yayitswei

Reputation: 4687

How to return a failed promise?

How would I return a promise but invoke its failure block immediately? Here's a gnarly way to do it:

if (fail) {
    var q = $q.deferred();

    $timeout(function() {
        q.reject("")
    }, 1);

    return q.promise;
} else {
  return $http.get("/").then(function(data) {});
}

Upvotes: 18

Views: 10992

Answers (2)

zloctb
zloctb

Reputation: 11194

function setLike(productId){
    return new Promise(function(succeed, fail) {
        if(!productId) throw new Error();
        jQuery.ajax({
            success: function (res) {
                succeed(res)
            }
        })
    })
}


    setLike(id).then(function(){

       //render

    }).catch(function(e){})

Upvotes: 1

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40318

if( fail ) {
    return $q.reject(yourReasonObject);
}
else ...

Ref here :)

Upvotes: 18

Related Questions