【问题标题】:How to return a failed promise?如何返回一个失败的承诺?
【发布时间】:2013-09-29 05:38:28
【问题描述】:

我如何返回一个 Promise 但立即调用它的失败块?这是一种很粗糙的方法:

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

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

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

【问题讨论】:

  • 你为什么要这样做?请发布所有代码块
  • 因为我想在调用者函数中调用catch块。
  • 这看起来不错。你面临的问题是什么。你是如何发现失败的?
  • 那么fail 是什么,您从其他承诺中获得了这个价值?,请发布更多信息
  • 您想在调用函数中调用catch 块吗?然后抛出一个异常并且不返回任何东西,比如throw new Error('Custom Message');

标签: javascript angularjs callback promise


【解决方案1】:
if( fail ) {
    return $q.reject(yourReasonObject);
}
else ...

参考here :)

【讨论】:

    【解决方案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){})
    

    【讨论】:

      猜你喜欢
      • 2015-11-27
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多