不管是 IONIC的,或者是angular的 都为异步HTTP,这样会导致一个问题,我下个接口的参数,会依赖于上个接口的返回值,如果为异步请求的话,只能在 .subscribe 或者 .then 里面获取返回值,然后再调用下一个接口,这样不仅响应代码的可阅读性,并且会导致多个嵌套,引发一系列问题。
下面介绍同步使用HTTP 方法
- 封装一个http 类,例如get方法
public getAsync(url: any): Promise<any> {
return new Promise((resolve, reject) => {
this.http.get(url).subscribe((data) => {
resolve(data);
}, (err: HttpErrorResponse) => {
resolve({
err: err.status,
message: "網絡錯誤"
});
});
})
}
2.利用 async/await 实现 HTTP 同步
在方法上面添加 async,在需要同步的代码前增加 await
例子:
public async login() {
console.log("1");
let val = await this.identifyApi.login("data=" + encodeURI("xxx"), this.config);
console.log("2");
let res = await this.identifyApi.getUserByPk(val, this.config);
console.log("3");
console.log("后续操作");
}
代码会按照顺序执行,如果不使用 该同步方法,则代码执行顺序为:
public login() {
console.log("1");
this.identifyApi.login("data=" + encodeURI("xxx"), this.config).then(res => {
console.log("2");
this.identifyApi.getUserByPk(res.xxx, this.config).then(data => {
console.log("3");
console.log("返回值");
console.log("后续操作");
});
});
}