在AngularJS $http.get中返回Promise?

3

我正在尝试返回从$http.get获取到的值,但无法使其起作用...

$scope.getDecision = function(id) {
    var defer = $q.defer();
    $http({
        method: 'GET',
        url: 'http://127.0.0.1:3000/decision',
        params: {id: id},
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data, status, header, config) {
        console.log(data); //----> Correct values
        defer.resolve(data);
    }).error(function(data, status, header, config) {
        defer.reject("Something went wrong when getting decision);
    });
    return defer.promise;
};

$scope.selectView = function(id) {
     var decision = $scope.getDecision(id);
     console.log(decision); //----> undefined
}

当我调用selectView时,我希望得到一个决定,但是我得到的只是未定义的...我是否误解了Promise模式?:S

是的,Promises 仍然是异步的。你不能 return 一个简单的值。 - Bergi
1
除了延迟反模式之外,这个应该仍然记录一个Promise对象而不是undefined - Bergi
2个回答

3

$http本身返回一个promise,无需自己创建,只需执行return $http(...)即可。


我删除了你的.get调用,因为OP正在使用带有选项对象的$http,希望你不介意 :) - CodingIntrigue

0

$http 无论如何都会返回一个 Promise,所以你实际上不需要创建自己的 Promise。但这个代码不起作用的主要原因是你仍然需要使用 .then 来调用你的 getDecision 方法,以便等待异步操作完成,例如:

$scope.selectView = function(id) {
     $scope.getDecision(id).then(function(decision) {
          console.log(decision);
     });
}

使用现有的$http承诺:

$scope.getDecision = function(id) {
    return $http({
        method: 'GET',
        url: 'http://127.0.0.1:3000/decision',
        params: {id: id},
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
};

谢谢,这个解释正是我所需要的 :)! - Cleaning

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接