在Angular JS中同步回调

时间:2016-03-12 02:24:28

标签: javascript angularjs callback

我正在尝试从服务和一个直接调用的同步两个回调。 (这是旧代码所以请忽略代码质量)

 if($scope.newUser.password == $scope.newUser.password2)
        {
            // search for the user to see if it already exists
            UserValidateService.findUserByEmail($scope.newUser.username, $scope.newUser.email, function(user){
                console.log(user);
                if(user[0]) {
                    alert('email Id already exists ******');
                    return false;
                }
            }).then(function(){ 
                $http.get("/api/user/"+$scope.newUser.username)
                .success(function(newUser) {
                    // if user does not exist, create it new
                    if(newUser.length == 0) {
                        $http.post("/api/user", $scope.newUser)
                        .success(function(newUser){
                            if(newUser == null)
                                alert("Unable to register user");
                            else
                                $location.path( $scope.newUser.username+"/home" );
                        });
                    }
                    else
                    {
                        alert("User already exists");
                    }
                });
            });
        }
        else
        {
            alert("Passwords must match. Try again");
        }

服务:

app.factory('UserValidateService', function($http){

    var findUserByEmail = function (user, email, callback) {
        $http.get("/api/user/"+user+"/email/"+email)
        .success(callback);
    };

    return {
        findUserByEmail: findUserByEmail
    };
});

错误:

TypeError: Cannot read property 'then' of undefined
    at h.$scope.register (user.js:118)
    at angular.js:10567
    at angular.js:18627
    at h.$eval (angular.js:12412)
    at h.$apply (angular.js:12510)
    at HTMLButtonElement.<anonymous> (angular.js:18626)
    at HTMLButtonElement.jQuery.event.dispatch (jquery.js:5095)
    at HTMLButtonElement.elemData.handle (jquery.js:4766)

任何请让我在哪里出错或如何使这段代码同步,即致电

1 个答案:

答案 0 :(得分:0)

您的UserValidateService没有返回承诺,它使用来自$http成功方法的回调。这是应该避免的anti-pattern

转换工厂以从$http服务返回承诺:

app.factory('UserValidateService', function($http){

    var findUserByEmail = function (user, email) {
        return $http.get("/api/user/"+user+"/email/"+email)
    };

    return {
        findUserByEmail: findUserByEmail
    };
});

然后使用promise的.then方法执行回调功能。

var promise = UserValidateService
                  .findUserByEmail($scope.newUser.username,
                                   $scope.newUser.email);

var derivedPromise = promise.then ( function(response){
    console.log(response.user);
    if(response.user[0]) {
        alert('email Id already exists ******');
    });
    //return response for chaining
    return response;
});

后续操作可以链接derivedPromise