美文网首页我爱编程
Angular Promises – Then Vs Succe

Angular Promises – Then Vs Succe

作者: 滚石_c2a6 | 来源:发表于2018-04-19 10:45 被阅读39次

    在angularjs 1.5中$http success和error方法已弃用。
    Simple calls with no chaining is usually no problem, but if you try to chain off a success handler you might be in for a surprise.

    The fundamental difference between 'success' and 'then' is that success will return the original promise instead of returning a new derived promise. Each then() invocation returns a fresh promise – which is key to chaining multiple promise calls.

    $http.get('/firstUrl')
        .success(function(response){
            console.log(response);
            //return 返回的数据不能被下面的success或者then取到,取到的一直是response。
            //This promise is returned in vain - no one cares about the result :-(
            return $http.get('/secondUrl')
        })
        .success(function(response){
            console.log('I only have access to the data from the first call');
            console.log(response);
        })
    

    如果想要通过success传值,可以通过deffered.resolve(data)

    function getList(){
    var deffered = $q.defer();
    $http.get('/firstUrl')
        .success(function(response){
            if (res.result == 0) {
                    deffered.resolve(res);
            } else {
                    deffered.reject('err');
            }
        })
        .error(function(err){
            deffered.reject('err');
        })
    return deffered.promise; //必须返回promise
    }
    

    如果用then就会简单很多

    function getList(){
    return $http.get('/firstUrl')  //必须加上return
        .then(function(response){
            if (res.result == 0) {
                    return res;
            } else {
                  return $q.reject('err');
            }
        })
        .catch(function(err){
            console.log(err);
        })
    }
    

    示例:

                var jsonp = function (apiKey, params, isCommon) {
                    var promise;
                    if (isCommon) {
                        promise = $http.jsonp(JOLLY_CONFIG['apiCommonUrl'], {
                            params: {
                                data: params,
                                url: JOLLY_CONFIG[apiKey],
                                callback: 'JSON_CALLBACK',
                            },
                        });
                    } else {
                        promise = $http.jsonp(JOLLY_CONFIG[apiKey] +
                            '?callback=JSON_CALLBACK', {
                            params: params,
                        });
                    }
                    return promise.then(function (res) {
                        var data = res.data;
                        if (data.result !== 0) {
                            return $q.reject(res);
                        } else {
                            return data;
                        }
    
                    });
                     .catch(function (res) {
                        if (res.status >= 200 && res.status < 300) {
                             showToast(res.data.message);
                         } else {
                              showToast($scope.requestError);
                          }
                    });
                };
    
    httpService.jsonp(
                            'validatePhoneNumber',
                            extendParams(validatePhoneNumberParams)).
                            then(function () {
    
                                // 发送手机短信
                                var sendSmsCodeParams = {
                                    phone: phone,
                                    countryNumber: code,
                                    useType: 5, //手机注册
                                    terminalType: urlParms['frm'], //pc平台
                                };
                                return httpService.jsonp('sendSmsCode',
                                    sendSmsCodeParams,
                                    true);
                            }).then(function (res) {
    
                            $state.go('code', {code: code, phone: phone});
    
                        }).catch(function (res) {
                            errorCallback(res);
                        });
    

    参考:http://www.syntaxsuccess.com/viewarticle/angular-promises%E2%80%93then-vs-success

    相关文章

      网友评论

        本文标题:Angular Promises – Then Vs Succe

        本文链接:https://www.haomeiwen.com/subject/aloikftx.html