【发布时间】:2015-02-16 00:26:56
【问题描述】:
我不明白 AngularJS 中的承诺的概念。我有两个功能:一个是获取远程设置配置,另一个是获取这个远程配置(存储在$scope)。我需要将它们分开,因为我在应用程序的其他部分使用不同的超时或调用。
我以为有了 Promise,一切都在运行,在这里我发现我的函数 fetch 在加载函数之前开始。为什么?为什么系统在等待下载我的设置,然后开始提取?
/* ----- $scope.sea.funcs.seaInit(); ----- */
$scope.sea.funcs.seaInit = function() {
// PROMISES ORDER
var deferred = $q.defer();
var promise = deferred.promise;
// 0 : get distant config
promise.then(function() {
/* ----- SERVICE ConfigService.generale(); ----- */
ConfigService.generale({call: 'yes'}, function(responseSC) {
// store datas
$scope.datas.shared.configuration = responseSC[0];
console.log('load end');
});
});
// 1 : fetch stored distant config
promise.then(function() {
$scope.sea.funcs.seaConfigFetch();
});
// final resolve
deferred.resolve('ok');
}
/* ----- $scope.sea.funcs.seaConfigFetch(); ----- */
$scope.sea.funcs.seaConfigFetch = function() {
console.log('fetch start');
// here i do operations with $scope ...
}
/* ----- $scope.sea.funcs.seaInit(); call ----- */
$timeout($scope.sea.funcs.seaInit, 3000);
这里,“获取开始”出现在“加载结束”之前。我将服务直接放在第一个承诺中,因为我认为这是问题,但不是。
$scope 值出现“未定义”错误。
【问题讨论】:
-
我会看:youtube.com/watch?v=o84ryzNp36Q 你对 Promise 的理解不太正确,这就是为什么你的例子没有按你预期的方式工作。
标签: javascript angularjs angular-promise