Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {});
}
like image 959
yayitswei Avatar asked Sep 24 '13 06:09

yayitswei


2 Answers

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

Ref here :)

like image 193
Nikos Paraskevopoulos Avatar answered Oct 31 '22 23:10

Nikos Paraskevopoulos


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){})
like image 1
zloctb Avatar answered Nov 01 '22 00:11

zloctb