我在写一个使某个http调用的角度服务。代码是这样的。多个API调用后的角度执行函数
this.checkAndSendNotifications = function() {
UsersService.getArray(function(array) {
var notifications = [];
angular.forEach(array, function(element) {
if (some conditions is true) {
srv.sendNotificationToToken(element.id,
function() {
notifications.push({
id: user.id,
errorStatus: null,
errorStatusText: null
});
},
function(error) {
notifications.push({
id: user.id,
errorStatus: error.status,
errorStatusText: error.statusText
});
});
}
});
printNotificationsStatus(notifications);
});
};
this.sendNotificationToToken = function(id, onSuccess, onError) {
$http({
method: 'POST',
url: 'https://url....',
headers: {
'Authorization': 'Bearer ....',
'Content-Type': 'application/json'
},
data: {
"id": id,
"message": "hello"
}
}).then(function successCallback(response) {
onSuccess();
}, function errorCallback(error) {
onError(error)
});
};
我需要调用printNotificationsStatus()函数只有在所有API的调用结束,以确保让所有的API响应,但现在被调用的函数在angular.forEach执行结束和API的承诺稍后可以解决,因为它们是异步的。
有没有办法等待?提前 达维德
看一看'$ q.all([承诺...])'https://docs.angularjs.org/api/ng/service/$ q#所有。你需要你的服务来返回一个承诺,以便你可以将它们推送到一个数组。 –
由于布鲁诺和cesaregb注意到我在printNotificationsStatus位置上犯了一个错误......坦克 –