Javascript Angular js:如何同步调用工厂/服务方法

Javascript Angular js:如何同步调用工厂/服务方法,javascript,jquery,html,angularjs,Javascript,Jquery,Html,Angularjs,在rum方法中,我调用工厂方法。当以秒为单位传递第一个方法的输出时 在这种情况下,如何同步执行这些方法 mycontroller.js (function () { "use strict"; angular .module("autoQuote") //Do initalization on page load .run(["$log","$rootScope","$state","dtoResource","questionResource"

在rum方法中,我调用工厂方法。当以秒为单位传递第一个方法的输出时

在这种情况下,如何同步执行这些方法

mycontroller.js

(function () {
    "use strict";

 angular
    .module("autoQuote")
        //Do initalization on page load
       .run(["$log","$rootScope","$state","dtoResource","questionResource",function($log,$rootScope,$state,dtoResource,"questionResource") { 
          $rootScope.AutoQuote = dtoResource.rc1Step1DTO();
          $rootScope.questions = questionResource.getQuestions($rootScope.AutoQuote.postAutoQuoteObj.SessionInfo.StateCode);
          console.log($rootScope);
          $rootScope.$on("$stateChangeSuccess", function(event, toState, toParams, fromState, fromParams) {
            if (fromState.name === "") { 

            }
          });
        }])
}()); 
dtoresource.js

(function () {
    "use strict";

    angular
        .module("autoQuote")
        .factory("dtoResource",["$resource",dtoResource]);

    function dtoResource($resource)
    {
        console.log('here in dto process.');
        var prepareAutoQuoteDTO = {        
        postAutoQuoteObj         : getAutoQuoteObject(),  
       /*
       * store session info
       */
       rc1Step1DTO : function(){
        var emailId = 'test1@gmail.com';
        if (emailId && emailId != '' && emailId != 'Email Address'){
            var email           = new Email();
            email.EmailTypeCd   = 'PRIMARY';
            email.EmailAddress  = emailId;
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
        } 
       return prepareAutoQuoteDTO;
     }, 

     rc1Step2DTO :  function(){
        /*
        * Store Driver information into array object
        * Collect driver info into local array and then reassign them to actual DTO object
        */
        this.postAutoQuoteObj.SessionInfo.UseExistingSession = false;
        this.postAutoQuoteObj.SessionInfo.PageName           = 'driver';
        this.postAutoQuoteObj.SessionInfo.PreviousPageName   = 'cars';
        //this.setCLK();
        return prepareAutoQuoteDTO;            
     }
    };
  return prepareAutoQuoteDTO;
}
}());
(function () {
    "use strict";

    angular
    .module("autoQuote")
    .factory("questionResource",["$resource","$http","$state",questionResource]);

    function questionResource($resource,$http,$state)
    {   
        return{
         getQuestions : function(stateCode) {
             var userState = stateCode != "" ? stateCode : 'CA';
             $http.get('assets/themes/easyquote/js/questions/'+userState+'.json')
             .then(function(response) {
                return response.data;  
            }); 
        }
       }
    }
}()); 
questionResource.js

(function () {
    "use strict";

    angular
        .module("autoQuote")
        .factory("dtoResource",["$resource",dtoResource]);

    function dtoResource($resource)
    {
        console.log('here in dto process.');
        var prepareAutoQuoteDTO = {        
        postAutoQuoteObj         : getAutoQuoteObject(),  
       /*
       * store session info
       */
       rc1Step1DTO : function(){
        var emailId = 'test1@gmail.com';
        if (emailId && emailId != '' && emailId != 'Email Address'){
            var email           = new Email();
            email.EmailTypeCd   = 'PRIMARY';
            email.EmailAddress  = emailId;
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
        } 
       return prepareAutoQuoteDTO;
     }, 

     rc1Step2DTO :  function(){
        /*
        * Store Driver information into array object
        * Collect driver info into local array and then reassign them to actual DTO object
        */
        this.postAutoQuoteObj.SessionInfo.UseExistingSession = false;
        this.postAutoQuoteObj.SessionInfo.PageName           = 'driver';
        this.postAutoQuoteObj.SessionInfo.PreviousPageName   = 'cars';
        //this.setCLK();
        return prepareAutoQuoteDTO;            
     }
    };
  return prepareAutoQuoteDTO;
}
}());
(function () {
    "use strict";

    angular
    .module("autoQuote")
    .factory("questionResource",["$resource","$http","$state",questionResource]);

    function questionResource($resource,$http,$state)
    {   
        return{
         getQuestions : function(stateCode) {
             var userState = stateCode != "" ? stateCode : 'CA';
             $http.get('assets/themes/easyquote/js/questions/'+userState+'.json')
             .then(function(response) {
                return response.data;  
            }); 
        }
       }
    }
}()); 
在autoQuotecontroller中,下面的行应该一个接一个地执行

$rootScope.AutoQuote = dtoResource.rc1Step1DTO();
          $rootScope.questions = questionResource.getQuestions($rootScope.AutoQuote.postAutoQuoteObj.SessionInfo.StateCode);

你需要利用承诺。你们工厂的每一种方法都应该有一个承诺。您可以使用
$q
来完成此操作

步骤1

$q
注入工厂。e、 g.让我们在
dtoResource
工厂这样做

    angular
     .module("autoQuote")
     .factory("dtoResource",["$resource",'$q', dtoResource]);

    function dtoResource($resource, $q)
    .....
 rc1Step1DTO : function(){
     var deferred = $q.defer();
      var emailId = 'test1@gmail.com';
      if (emailId && emailId != '' && emailId != 'Email Address'){
        var email           = new Email();
        email.EmailTypeCd   = 'PRIMARY';
        email.EmailAddress  = emailId;
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
       deferred.resolve(prepareAutoQuoteDTO);
       } 
      return deferred.promise;
   }
 dtoResource.rc1Step1DTO()
 .then(questionResource.getQuestions)
 .then(function(){
   console.log('This should be printed after the above methods are done     executing');
  })
.fail(function(reason){
  console.log(reason + ' this is the reason that your code failed. The reason comes from a defered.reject from your chained methods');
 });
步骤2

让方法返回这样的承诺

    angular
     .module("autoQuote")
     .factory("dtoResource",["$resource",'$q', dtoResource]);

    function dtoResource($resource, $q)
    .....
 rc1Step1DTO : function(){
     var deferred = $q.defer();
      var emailId = 'test1@gmail.com';
      if (emailId && emailId != '' && emailId != 'Email Address'){
        var email           = new Email();
        email.EmailTypeCd   = 'PRIMARY';
        email.EmailAddress  = emailId;
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
       deferred.resolve(prepareAutoQuoteDTO);
       } 
      return deferred.promise;
   }
 dtoResource.rc1Step1DTO()
 .then(questionResource.getQuestions)
 .then(function(){
   console.log('This should be printed after the above methods are done     executing');
  })
.fail(function(reason){
  console.log(reason + ' this is the reason that your code failed. The reason comes from a defered.reject from your chained methods');
 });
第二个函数(prepareAutoQuoteDTO)所需的参数需要传递给deferred.resolve,以便可用于链中的下一个函数

步骤3 转换所有工厂方法(需要同步执行)以返回如上所述的承诺

步骤4 像这样在控制器中调用这些方法

    angular
     .module("autoQuote")
     .factory("dtoResource",["$resource",'$q', dtoResource]);

    function dtoResource($resource, $q)
    .....
 rc1Step1DTO : function(){
     var deferred = $q.defer();
      var emailId = 'test1@gmail.com';
      if (emailId && emailId != '' && emailId != 'Email Address'){
        var email           = new Email();
        email.EmailTypeCd   = 'PRIMARY';
        email.EmailAddress  = emailId;
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
        this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
       deferred.resolve(prepareAutoQuoteDTO);
       } 
      return deferred.promise;
   }
 dtoResource.rc1Step1DTO()
 .then(questionResource.getQuestions)
 .then(function(){
   console.log('This should be printed after the above methods are done     executing');
  })
.fail(function(reason){
  console.log(reason + ' this is the reason that your code failed. The reason comes from a defered.reject from your chained methods');
 });
记住

  • 代码的所有可能分支都必须解析或拒绝承诺
  • 使用deferred.resolve或reject将参数传递给链接函数
  • fail
    步骤中处理控制器中的故障情况
  • 明智地使用承诺

您需要从函数
rc1Step1DTO
返回a。然后,您可以使用这样的代码:
$rootScope.AutoQuote=dtoResource.rc1Step1DTO()。然后(function(){;$rootScope.questions=questionResource.getQuestions($rootScope.AutoQuote.postAutoQuoteObj.SessionInfo.StateCode);})谢谢,如何在上面的代码中添加承诺。有allready。然后在factory.is@Srijith中回答您的问题吗?我将代码更改为$rootScope.AutoQuote=dtoResource.rc1Step1DTO()。然后($rootScope.questions=questionResource.getQuestions('CA');console.log($rootScope);)语法错误:缺少)在参数列表之后。这里我缺少什么。
dtoResource.rc1Step1DTO().then(questionResource.getQuestions)。然后(function(){console.log('done'))在工厂中的各个方法中设置rootscope值。在
rc1Step1DTO
中,执行
deferred.resolve('CA')
,以便将其作为参数提供给
questionResource.getQuestions
resolved$rootScope.AutoQuote=dtoResource.rc1Step1DTO()。然后(function(){$rootScope.questions=questionResource.getQuestions('CA');console.log($rootScope)然后(function(){console.log('应该在执行上述方法之后打印');}),但在控制台中,我看到ajax请求是在打印“应该在执行上述方法之后打印”。ajax响应应该出现,然后只打印此日志。确保
getQuestions
方法也返回承诺。注释中的上述代码将异步执行
getQuestions
,除非像我的答案中那样将其链接到
rc1Step1DTO
方法。