【发布时间】: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