【问题标题】:Asynchronous function inside asynchronous function异步函数内部的异步函数
【发布时间】:2017-01-19 01:42:07
【问题描述】:

我在函数中有这段代码:

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

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

 @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)) {) 中的异步函数?

【问题讨论】:

  • 首先,你需要valCategories 来返回一个 Promise,或者接受一个回调参数——事实上,你没有机会改变顶部块来使用那个函数——顺便说一下,第二块是什么语言?这不是javascript
  • @JaromandaX 我正在使用打字稿。对于误导性的 es6-promise 标签,我们深表歉意。明天我会在工作中回到这个问题并尝试一下,底部的代码块在下面的答案中。干杯

标签: javascript asynchronous typescript promise


【解决方案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 应该返回一个承诺或允许你传递一个回调来做这样的事情:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 2021-02-20
    • 2021-02-23
    • 2023-03-22
    相关资源
    最近更新 更多