提问者:小点点

异步函数内部的异步函数


我在一个函数中有这样的代码块:

this.apiService.fetchCategories(!this.cacheData).subscribe(
    response => {
        if(this._jsnValService.valCategories(response)) {
            this.customerMap.categories = this.formatCategories(response["categories"]);
        } else {
            alert("Categories failed the schema validation. Please contact support if this happens again.");
        }
    },
    error => {
        this.notification.title = "Oops, there's a problem.";
        this.notification.content = "Seems there's an issue getting the provider categories.";
        this.notification.show("provider_categories_api");
    }
);

它获取一些数据,然后对数据运行验证(if(this._jsnvalservice.valcategories(response)){)。

但是,我对数据的验证实际上也是异步的,因为它是根据一个json模式来验证数据的,而json模式位于一个独立的json文件中,所以它必须首先读取该文件。

我使用了一个承诺来读取文件内容,然后进行验证:

 @Injectable()
 export class ValidateJSONSchemaService {

     constructor(private http: Http) {}

     public valCategories(json) {
         this._getSchema("./jsonSchema.categories.json").then((schema) => {
             this._valSchema(json, schema);
         });
     };

     private _valSchema(json, schema): any {
         var ajv = new Ajv();
         var valid = ajv.validate(schema, json);
         if (!valid) {
             console.log(ajv.errors);
             return false;
         } else {
             console.log(valid);
             return true;
         };
     };

     private _getSchema(fileName): any {
         return new Promise((resolve, reject) => {
             this.http.get(fileName)
                 .map(this._extractData)
                 .catch(this._handleError)
                 .subscribe(schema => resolve(schema));
         });
     };

     private _extractData(res: Response) {
         let body = res.json();
         return body.data || {};
     };

如何编辑此问题中的顶部代码块以解释if语句(if(this._jsnvalservice.valcategories(response)){)中的异步函数?


共1个答案

匿名用户

如果您使用的是ES6,您可以使用Async/Await,如下所示:

async function _validateCategories() {
  this.apiService.fetchCategories(!this.cacheData).subscribe(
    response => {
        const valid = await this._jsnValService.valCategories(response)
        if(valid) {
            this.customerMap.categories = this.formatCategories(response["categories"]);
        } else {
            alert("Categories failed the schema validation. Please contact support if this happens again.");
        }
    },
    error => {
        this.notification.title = "Oops, there's a problem.";
        this.notification.content = "Seems there's an issue getting the provider categories.";
        this.notification.show("provider_categories_api");
    }
  );
}

如果不是,函数fetchCategories应该返回一个promise或者允许您传递一个回调来执行以下操作:

async function _validateCategories() {
  this.apiService.fetchCategories(!this.cacheData).subscribe(
    response => {
        this._jsnValService.valCategories(response).then((error, valid)=> {
        if(error) {
            alert("Categories failed the schema validation. Please contact support if this happens again.");
        }
        this.customerMap.categories = this.formatCategories(response["categories"]);
        })
    },
    error => {
        this.notification.title = "Oops, there's a problem.";
        this.notification.content = "Seems there's an issue getting the provider categories.";
        this.notification.show("provider_categories_api");
    }
  );
}

相关问题