如何从处理程序方法/函数中拒绝承诺

时间:2017-06-26 19:58:19

标签: javascript angularjs angular-promise

我目前正在使用新的ES6类语法在angularJS(v1.4.14)中构建一个服务,并且有一个链接/展平的promise树,其中包含3 .then()'

ui-router正在解析setCampaign()方法。如果数据有问题(例如下面的例子中没有id字段)我想拒绝承诺,以便路由器' $ stateChangeError' listener获取被拒绝的对象并重定向到错误状态。

如果出现问题,我会如何拒绝承诺(并打破链条)。

我知道如果我不将我的处理程序提取到不同的方法名称,我可以使用$ q.reject:

setCampaign(){
  let deferred = this._$q.defer();

  this._ApiService.get({entity: 'campaign'}).$promise.then(
    campaignResponse => {
        if (campaignResponse.status == 'success' && campaignResponse.data.id){
            //assign to the campaign property and return to next .then()                
            this.campaign = campaignResponse.data

            //call next promise
            this.Api.get({entity: 'campaign-info', entity_id: campaignResponse.data.id }).$promise.then(

                //handle response and get forever more indented ugly code
                campaignInfoResponse => {
                    //do more stuff ...
                    return deferred.resolve(data);
                }
            )

        }
        //break the chain
        return deferred.reject(({status:"error", message: "blah blah"})
    });
  return deferred.promise
}

但我想编写的代码不会缩减到百万度,看起来更优雅。当我这样做时,我似乎无法拒绝承诺。有人可以帮忙吗?

class CampaignService{
    constructor($q, ApiService){
        'ngInject';
        this._$q = $q;
        this._ApiService = ApiService;
    }

    setCampaign(){
        return this._ApiService.get({entity:'campaign'})
            .then(this.assignCampaign)
            .then(this.getCampaignTheme)
            .then(this.assignTheme)
            .catch(this.errorHandler);
    }


    assignCampaign(campaignResponse){

        if(campaignResponse.status == 'success' && campaignResponse.data.id){
            //assign to the campaign property and return to next .then()
            this.campaign = campaignResponse.data
            return campaignResponse.data
        }

        //break the chain
        return this._$q.reject({status:"error", message: "blah blah"})
    }
}

0 个答案:

没有答案