我有一个应该返回promise的AngularJS服务方法。在该方法中是异步调用,在成功时继续执行$ http调用。我的语法不正确,无法正确返回。
// This function should return a promise
function doFacebook() {
var deferred = $q.defer();
Facebook.login(function(response) {
var p = $http({
method: 'POST',
url: '/auth/facebook',
data: {
token: response.authResponse.accessToken
}
});
p.then(function(data) {
startSession(data);
return data;
}, function(data) {
return $q.reject(data);
});
});
return deferred.promise;
}
我想要返回p - 不确定如何附加/替换延迟p。
答案 0 :(得分:0)
您可以使用facebook登录回调中的http调用返回的promise p
来解析延迟对象。它应该自动解决/拒绝传入的承诺。
function doFacebook() {
var deferred = $q.defer();
Facebook.login(function(response) {
var p = $http({
method: 'POST',
url: '/auth/facebook',
data: {
token: response.authResponse.accessToken
}
}).then(function(data) {
startSession(data);
return data;
}, function(data) {
return $q.reject(data);
});
//Here
deferred.resolve(p);
});
return deferred.promise;
}
示例演示: -
///BAD CODE ALERT!!
angular.module('app', []).controller('ctrl', function($scope, $q, $http, $timeout) {
function doAsync() {
var deferred = $q.defer();
//Simulating non angular async
setTimeout(function() {
//Simulating http call. $timeout also returns a promise, so.
var p = $timeout(function() {
//uncomment to test reject scenario
if ($scope.reject) {
$scope.reject = false;
throw Error("OOPS i got rejected");
}
return 'Hello, i got resolved!!'
}).then(function(data) {
return data;
}, function(data) {
return $q.reject(data.message);
});
//Here
deferred.resolve(p);
});
return deferred.promise;
}
$scope.runTest = function() {
doAsync().then(function(data) {
$scope.data = data;
}).catch(function(error) {
$scope.data = error;
});
}
$scope.rejectTest = function() {
$scope.reject = true;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<button ng-click="rejectTest()">Reject and then</button>
<button ng-click="runTest()">Run Test</button>
<div>{{data}}</div>
</div>