defer.promise打印出对象而不是数据

时间:2014-10-20 13:44:28

标签: angularjs

我有这段代码:

app.factory('loadDependencies', function ($q, $timeout) {

    return {
        load: function () {
            console.log("start 1");
            var defer = $q.defer();


            $timeout(function () {
                defer.resolve({ resolve: "got dependencies" });
            }, 3000);

            return defer.promise;

        }
    }
});

但问题是defer.promise不会等到超时结束,而且它只是打印出对象属性而不是数据,它打印出来:

Object { then: qFactory/defer/deferred.promise.then(), catch: qFactory/defer/deferred.promise.catch(), finally: qFactory/defer/deferred.promise.finally() }

我是棱角分明的新手并试图了解我做错了什么?

修改

有关我想要完成的更多信息。

我在路由中有决心动态加载控制器和css文件。

.when('/url', {
        templateUrl: 'someview',
        controller: 'somecontroller',
        resolve: {
            load: function (loadDependencies) {
                loadDependencies.load(); // here i need to know get the result of what's inside $timeout of 'load'
            }
        }

    })

1 个答案:

答案 0 :(得分:1)

这是因为defer.promise不会返回您的数据,也不会等到您的timeout完成。那么你用它做什么就是分配一些处理程序并等待它完成/失败:

function success(data) {
    //this is called after defer.resolve({ resolve: "got dependencies" }); gets executed
    //here you can access your data
}

function error(error) {
    //this is called if the promise gets rejected
}

loadDependencies.load().then(success, error);

现在,当您的承诺完成时,它会自动调用其中一个处理程序。应用回调的可能性更多,例如.finally()方法。看看documentation

修改

只需在解析器中返回承诺:

.when('/url', {
        templateUrl: 'someview',
        controller: 'somecontroller',
        resolve: {
            load: function (loadDependencies) {
                return loadDependencies.load(); // here i need to know get the result of what's inside $timeout of 'load'
            }
        }
    })

现在在解析promise之后将调用控制器,angular会将解析后的值传递给它,如下所示:

app.controller("CtrlName", function($scope, load){
    //access your load value here
});