How to return a failed promise?

10,412

Solution 1

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

Ref here :)

Solution 2

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){})
Share:
10,412

Related videos on Youtube

yayitswei
Author by

yayitswei

hacking away in the Bay

Updated on October 18, 2022

Comments

  • yayitswei
    yayitswei about 1 year

    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) {});
    }
    
    • Chandermani
      Chandermani
      This seems fine. What is the problem you are facing. How are you catching the failure?