2014-11-01 102 views
1

我有,我用它來從我的Web服務器上獲取數據的方法:如何從異步方法返回同步回覆?

getUserTestQuestions = (testId): ng.IPromise<any> => { 
    var self = this; 
    var defer = this.$q.defer(); 
    this.$http({ 
     url: '/api/UserTestQuestion/GetAll/' + testId, 
     method: "GET" 
    }) 
     .success(function (data: IUserTestQuestion[]) { 
      self.qs = data; 
      defer.resolve(); 
     }) 
     .error((data: any, status: number, headers: (headerName: string) => string, config: ng.IRequestConfig): void => { 
      self.$ers.http(data, status, headers, config); 
      defer.reject(); 
     }) 
    return defer.promise; 
} 

它返回它用來調用者的承諾。

我想修改它,以便它只返回來自Web服務器的數據,如果數據不存在。要做到這一點,我想添加一個這樣的支票:

getUserTestQuestions = (testId): ng.IPromise<any> => { 
    var self = this; 
    var defer = this.$q.defer(); 

    if (question.downloaded) { 
     defer.resolve(); // I am doing a resolve here but is it the correct way 
         // as I think it will happen before the defer.promise 
         // is returned? 
    } else { 

     this.$http({ 
      url: '/api/UserTestQuestion/GetAll/' + testId, 
      method: "GET" 
     }) 
     .success(function (data: IUserTestQuestion[]) { 
      self.qs = data; 
      defer.resolve(); 
     }) 
     .error((data: any, status: number, headers: (headerName: string) => string, config: ng.IRequestConfig): void => { 
      self.$ers.http(data, status, headers, config); 
      defer.reject(); 
     }) 
    } 
    return defer.promise; 
} 

這是一個有效的方法來做到這一點?當我沒有異步地做任何事情時,立即返回解決方案似乎很奇怪。

回答

2

你應該使用$q.when,如果你想,如果數據已經存在

getUserTestQuestions = (testId): ng.IPromise<any> => { 

    if (question.downloaded) { 
     return $q.when(data) // I am doing a resolve here but is it the correct way 
         // as I think it will happen before the defer.promise 
         // is returned? 
    } else { 

    var self = this; 
    var defer = this.$q.defer(); 

    this.$http({ 
      url: '/api/UserTestQuestion/GetAll/' + testId, 
      method: "GET" 
     }) 
     .success(function (data: IUserTestQuestion[]) { 
      self.qs = data; 
      defer.resolve(); 
     }) 
     .error((data: any, status: number, headers: (headerName: string) => string, config: ng.IRequestConfig): void => { 
      self.$ers.http(data, status, headers, config); 
      defer.reject(); 
     }) 
    return defer.promise; 
    } 
} 

這樣主叫方總是可以做

getUseTestQuestion(testId).then() 

注意,$q.when返回輸出/現有數據返回承諾

+0

只是一個說明....我沒有發現'.when()'之前...有趣的方法 – 2014-11-01 16:11:26

+0

我用它很多,用於維護靜態數據,一次從數據庫中獲取。好處是,你的調用方法不知道數據庫是從數據庫還是從內存中...所以他們不知道如何實現或使用$資源... – harishr 2014-11-01 16:13:50