Javascript 如何从JSON对象内的promise返回数据?安格拉斯
这是我第一次尝试从JSON对象内的promise返回数据,我坚持执行此任务 通常的做法是这样的 服务jsJavascript 如何从JSON对象内的promise返回数据?安格拉斯,javascript,angularjs,promise,Javascript,Angularjs,Promise,这是我第一次尝试从JSON对象内的promise返回数据,我坚持执行此任务 通常的做法是这样的 服务js app.factory("dataService", ["$http", function ($http) { function getData(id) { return $http.get('endpoint', id) .then(function (response) { return res
app.factory("dataService", ["$http",
function ($http) {
function getData(id) {
return $http.get('endpoint', id)
.then(function (response) {
return response.data
});
}
return {
getData: getData
}
}])
控制器js
$scope.data = {}
dataService.getData($routeParams.id)
.then (function (res) {
$scope.data = res
});
angular.forEach($scope.properties, function (item) {
$scope.data.properties.push({
order: item.number,
name: item.name,
value: item.value,
items: $scope.getProp(item.id)
})
});
$scope.getProp = function (id) {
return dataService.single(id)
.then (function (res) {return res});
};
这很好,大家都很高兴
现在,我尝试在对象内部分配数据
控制器js
$scope.data = {}
dataService.getData($routeParams.id)
.then (function (res) {
$scope.data = res
});
angular.forEach($scope.properties, function (item) {
$scope.data.properties.push({
order: item.number,
name: item.name,
value: item.value,
items: $scope.getProp(item.id)
})
});
$scope.getProp = function (id) {
return dataService.single(id)
.then (function (res) {return res});
};
服务js
function single(id) {
return $http.get('endpoint' + "/" + id)
.then(function (response) {
return response.data
})
}
现在我得到了包含promise和$$state的JSON对象
我理解这个问题的本质,但这个问题的解决方案超出了我的知识范围,所以有人能帮我解决吗 使其发挥作用的一种方法是:
$scope.data.properties = [];
var promiseList = $scope.properties.map(function(item) {
var promise = $scope.getProp(item.id);
return promise.then(function (data) {
var newItem = {
id: item.id,
order: item.number,
name: item.name,
value: item.value,
items: data
};
$scope.data.properties.push(newItem);
return newItem;
});
});
$q.all(promiseList).then(function(itemList) {
console.log(itemList);
//More code here
});
上面的示例创建了一个承诺列表,这些承诺返回的对象具有items
属性,其中填充了从$scope.getProps
返回的承诺中的数据
此外,它还将每个填充的项推送到范围中。因为异步XHR可能不会按照启动顺序完成,所以作用域列表可能与原始列表的顺序不同
但是,将等待所有XHR完成并按原始顺序返回列表。@4castle所以您建议我使用回调?push语句应该位于
$scope.getProp(item.id)的回调函数中。然后,
@4castle得到了您,谢谢,没有问题。另外,您的代码目前没有这个问题,但请注意不要将其添加到当前正在迭代的列表中,否则可能会得到一个无限循环。