如何从异步方法返回同步回复?

时间:2014-11-01 07:34:17

标签: angularjs

我有一种方法可用于从我的网络服务器获取数据:

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;
}

它返回调用者使用的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;
}

这是一种有效的方法吗?当我实际上没有异步地执行任何操作时,立即返回解决方案似乎很奇怪。

1 个答案:

答案 0 :(得分: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返回输出/现有数据