MrW*_*and 1 javascript promise angularjs q
我调用了一个函数,该函数返回一个带有我想在链式调用中使用的 ID 的列表。一切似乎都在工作,直到我想读取所有返回的对象。那些是承诺,但我不知道为什么我无法解决它们。
//Get bubbles and then it calls another function getBubbleMessage with result from previous and last getBubbleMessage returns an array of promises.
$scope.loadStartPage = function () {
$scope.getBubblesThatUserHasAccessTo().then($scope.getBubbleMessage).then(function (data) {
$log.info("INFO:: " + data);
$scope.bubblesWithMessages = data;
});
};
$scope.getBubblesThatUserHasAccessTo = function () {
var deferred = $q.defer();
BubblesService.getBubblesUserAccess().then(function (result) {
deferred.resolve(result);
});
return deferred.promise;
};
Run Code Online (Sandbox Code Playgroud)
此函数正在获取一些我们需要解析连接到上述服务返回的 id:s 的消息的东西
$scope.getBubblesThatUserHasAccessTo = function () {
var deferred = $q.defer();
BubblesService.getBubblesUserAccess().then(function (result) {
deferred.resolve(result);
});
return deferred.promise;
};
Run Code Online (Sandbox Code Playgroud)
此函数获取所有消息并返回承诺对象 - 而这些我无法解决??
$scope.getBubbleMessage = function (data) {
var deferred = $q.defer();
var promises = [];
angular.forEach(data, function (item) {
$log.info("DDD" + item.name);
var promise = BubblesService.getBubbleMessages(item.id, 0, 1);
promises.push(promise);
});
//return $q.all([promises]);
$q.all([promises]).then(function (result) {
$log.info(result);
return result[0];
});
};
Run Code Online (Sandbox Code Playgroud)
上面的函数返回一个包含 60 个对象的数组。

最后,我想在页面上的 ng-repeat 中使用一个新对象。我真的认为这是我对 angular 和 promise 不熟悉的事情......但是经过几个小时的尝试解决这个问题后,我真的需要帮助:)
$q.all 接受一组承诺。在这里,您正在执行 $q.all([myPromises]),它会立即解决,因为 '[myPromise]' 是一个数组而不是一个承诺(当您给一个数组参数时,第一个也是唯一的元素是一个承诺数组)应该简单地使用promise数组。所以[]而不是[[]])。第二个问题:你没有在父函数中返回这个承诺。
你应该简单地改变块
$q.all([promises]).then(function (result) {
$log.info(result);
return result[0];
});
Run Code Online (Sandbox Code Playgroud)
和
return $q.all(promises);
Run Code Online (Sandbox Code Playgroud)
这将解决数组中的每个承诺的数组。
| 归档时间: |
|
| 查看次数: |
3667 次 |
| 最近记录: |