【问题标题】:AngularJS Defer.promise not working as expectedAngularJS Defer.promise 没有按预期工作
【发布时间】:2014-02-24 11:39:02
【问题描述】:

我正在使用 AngularJSPersistenceJS 开发应用程序。

我在处理异步调用时遇到了麻烦

控制器

cars.controller('CrashWidgetOneCtrl',function($scope, $location, $routeParams, CrashServices){  
    if($routeParams.crashId){
        $scope.data = {};
        console.log("CrashID: "+$routeParams.crashId);
        crashId = $routeParams.crashId; 
        alert(1);//Works

        CrashServices.getCrashDetails($scope, crashId).then(function(result){
            console.log(result);
            alert(2);//Never Fires
        });    
    alert(3);//Gets executed
    }else{
        console.log("N");
    }   

});

服务

cars.factory('CrashServices', function($http, $location, $q, CommonServices,$rootScope, $timeout){
    return{
        getCrashDetails:function($scope, crashId){
        var deferred = $q.defer();          
        // Get user details if any
        $scope.$apply(function(){
            var crashInfoTable = App.CrashInfoTable.all();
            alert(4);
            crashInfoTable.list(null, function (results) { 
                alert(5);//This also doesn't work
                deferred.resolve();
            }); 
        });
        return deferred.promise;
        }
    }

});

任何帮助将不胜感激。非常感谢。

注意:我正在使用 PersistenceJS。

【问题讨论】:

  • 我猜 App.CrashInfoTable.all() 也是一个异步调用。返回类型是什么?也是一个承诺?
  • 如果 crashInfoTable 的回调没有被调用,那么 promise 就不会被解析。所以 Defer.promise 确实按预期工作。在解决之前它不会触发成功回调函数。也许模型有问题?看看这个链接groups.google.com/forum/#!topic/persistencejs/eIfuqyXK09E
  • @michael: App.CrashInfoTable.all() 不是异步的。我不确定返回类型...我怎么知道?
  • @RoyMJ 而不是 alter(4) 你应该做 console.log(crashInfoTable);

标签: javascript angularjs persistence promise deferred


【解决方案1】:

我不知道你是否需要 scope.apply。 这似乎对我有用:

getCrashDetails:function($scope, crashId){
    var deferred = $q.defer();          
    // Get user details if any
    App.CrashInfoTable.all().list(null, function(results) { 
        deferred.resolve(results);
    });
    return deferred.promise;
}

【讨论】:

  • 是的..这确实是我最终做的..这是回来了..;)...谢谢..感谢它..
  • ...就像灰烬中的凤凰;)认为它可能会帮助遇到同样问题的其他人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
  • 2016-09-25
  • 2015-09-22
  • 2013-05-14
相关资源
最近更新 更多