【发布时间】:2017-07-25 14:22:51
【问题描述】:
我的问题是我的函数没有等待http请求的响应而走得更远。我知道我可以使用 promise 来等待,但我不明白这个概念。
我有一个包含所有 http 请求的数据服务:
function GetGroupIdFromBakery(bakeryId, successCallback, errorCallback) {
$http.get(service.baseUrl + "BakeriesGroup/Bakeries/" + bakeryId)
.then(function (result) { successCallback(result.data); }, errorCallback);
}
从另一个服务,我调用数据服务:
var hasPermission = function (permission, params) {
permissionRoute = permission;
setIdEntity(params);
for (var i = 0; i < permissions.length; i++) {
if (permissionRoute.Name === permissions[i].Name) {
if (permissions[i].Scope == "System")
return true;
else if (permissions[i].Scope == permissionRoute.Scope && permissions[i].IdEntity == permissionRoute.IdEntity)
return true;
}
}
return false;
}
var setIdEntity = function (params) {
if (permissionRoute.Scope == "Bakery")
permissionRoute.IdEntity = parseInt(params.bakeryId);
else if (permissionRoute.Scope == "Group") {
if (params.bakeriesGroupId)
permissionRoute.IdEntity = parseInt(params.bakeriesGroupId);
else {
getGroupOfBakery(parseInt(params.bakeryId));
}
console.log(permissionRoute.IdEntity);
}
}
var getGroupOfBakery = function (bakeryId) {
DataService.GetGroupIdFromBakery(bakeryId, function (groupId) {
permissionRoute.IdEntity = groupId;
}, function (error) {
console.error("something went wrong while getting bakery");
alert("Une erreur s'est produite lors de la récupération de la boulangerie");
});
}
我必须等待 DataService.GetGroupIdFromBakery() 的响应。使用此代码,当我调用 getGroupByBakery() 时,permission.EntityId 未定义。
有人可以帮帮我吗?
【问题讨论】:
-
你不能那样做。你需要使用承诺。
-
可以使用回调吗?
-
也许我错了,但对我来说,承诺是回调。我确信它们在引擎盖下是相同的。不管怎样,你说“
I know that I can use promise to wait but I don't understand the concept”;一开始我也没有,然后我开始认为它们在功能上完全相同,然后它就响了。纯粹主义者可能不同意 ;-) 但是,如果它对您有帮助,请将 pronises 视为回调
标签: angularjs