异步函数内的异步函数

时间:2017-01-19 01:42:08

标签: javascript asynchronous typescript promise

我在函数中有这段代码:

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模式验证它,因此它必须首先读取该文件。

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

 @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 个答案:

答案 0 :(得分:0)

如果您使用的是ES6,可以像这样使用async / await:

node

如果没有,你的函数fetchCategories应该返回一个promise或允许你传递一个回调来做这样的事情:

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