【问题标题】:Order and timing for promises in AngularJSAngularJS 中 Promise 的顺序和时间
【发布时间】: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 值出现“未定义”错误。

【问题讨论】:

标签: javascript angularjs angular-promise


【解决方案1】:

有了上面的内容,您定义了 1 个承诺并附加了两个要在解决时调用的函数,我认为您想要的是在 ConfigServices.generale 完成后调用 seaConfigFetch。为此,您可以更新以下内容:

/* ----- $scope.sea.funcs.seaInit(); ----- */
$scope.sea.funcs.seaInit = function() {

    // PROMISES ORDER
    var deferred = $q.defer();
    var promise = deferred.promise;
    // 0 : get distant config
    /* ----- SERVICE ConfigService.generale(); ----- */
    ConfigService.generale({call: 'yes'}, function(responseSC) {
        // store datas
        $scope.datas.shared.configuration = responseSC[0];
        console.log('load end');
        // final resolve
        deferred.resolve('ok');
    });
    // 1 : fetch stored distant config
    promise.then(function() {
        $scope.sea.funcs.seaConfigFetch();
    });
}

如果 ConfigService.generale 返回一个承诺,您可以进一步简化它以删除您创建的 $q.defer()。或者完全删除 promise 并在你有 deferred.resolve 的地方调用 seaConfigFetch。这是一篇关于带有 Promise 的常见反模式的好文章:http://taoofcode.net/promise-anti-patterns/

【讨论】:

    猜你喜欢
    • 2017-07-13
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2016-08-07
    • 2020-03-13
    相关资源
    最近更新 更多