我正在使用Ionic 4编写Ionic应用程序,但在使Promises按正确顺序执行时遇到了一些麻烦(或者也许我只是在考虑这个错误)。这也是我第一次使用Typescript,所以请多多包涵。
该应用程序需要与使用Oauth的API交互。我正在使用离子存储存储Oauth令牌,该存储还使用Promises进行获取/设置,因此这增加了我的问题。
如果使用以下文件片段:
oauth.service.ts:
export class OauthService {
...
public async setTokens(token: string, token_secret: string) {
return Promise.all([this.storage.set('token', token), this.storage.set('token_secret', token_secret)]);
}
public async getTokens() {
return Promise.all([this.storage.get('token'), this.storage.get('token_secret')]);
}
...
}
api.service.ts:
export class ApiService {
...
public async getCustomer() {
const requestData = {
.. request data ..
};
return this.authorisedRequest(requestData);
}
private authorisedRequest(requestData) {
return this.oauth.getTokens().then(([token, token_secret]) => {
if (!token || !token_secret) {
return Promise.reject('Tokens not available');
}
const tokens = {
'key': token,
'secret': token_secret
};
const oauthHeader = this.oauth.createHeader(requestData, tokens);
const headers = this.createHeaders({
'Authorization': oauthHeader.Authorization
});
return this.apiRequest(requestData.method, requestData.url, {}, headers);
}).catch((error) => {
// @todo what to do here, if anything?
console.info('token error:', error)
});
}
private async apiRequest(type, path, data, headers = null) {
if (!headers) {
headers = this.headers;
}
const response = new Subject();
const httpRequest = new HttpRequest(
type,
path,
data,
{
headers: headers
}
);
this.http.request(httpRequest).subscribe((res: any) => {
if (res.type) {
response.next(res.body);
}
}, error => {
const responseError = error.error.messages.error[0];
this.alerter.presentAlert(responseError.message);
response.error(error);
});
return response;
}
}
authentication.service.ts:
export class AuthenticationService {
...
public checkAuth() {
this.api.getCustomer().then((request: Subject<any>) => {
// this still executes but request is undefined.
request.subscribe((resp: any) => {
this.isLoggedIn = true;
}, (error) => {
this.isLoggedIn = false;
});
});
}
...
}
在大多数情况下,在令牌确实存在且不会拒绝诺言的情况下,这都是可行的。
但是,当我在init上运行checkAuth()(以检查用户是否已登录)时,getTokens()承诺会返回拒绝,该拒绝会被立即捕获(在api.service中),但checkAuth中的“ then”为即使应该捕获它仍然可以运行,这给了我一个错误:
TypeError: Cannot read property 'subscribe' of undefined
我可以将catch块移到checkAuth函数内部,但这意味着我必须在所有进行API调用(〜30个奇数端点)的情况下都这样做,这并不理想。
一无所获,我得到了这个错误:
Uncaught (in promise): Tokens not available
如何使拒绝失败静默失败,或者仅通过checkAuth传递错误?
还是我会完全以错误的方式进行此过程?我确实有一种感觉,我的oauth令牌检索过程在这里是错误的(导致对任何api调用的嵌套承诺)。
答案 0 :(得分:1)
主要问题是您将Observables
与Promises
混合使用错误的方式。
为简单起见,我建议一次只使用其中之一。
简单解决方案:
checkAuth() {
this.api.getCustomer()
.then((request: Subject<any>) => request.toPromise())
.then(() => { this.isLoggedIn = true; })
.catch(() => { this.isLoggedIn = false; });
}
或
import { from } from 'rxjs';
checkAuth() {
const customersObservable = from(this.api.getCustomer());
customersObservable.subscribe(
() => { this.isLoggedIn = true; },
() => { this.isLoggedIn = false; }
);
}
更好的解决方案:
使用较低的Promises或Observables来使服务的API清晰可见。
converting Observables into Promises的示例:
export class OauthService {
public async getTokens(): Promise<any> { ... }
}
export class ApiService {
public async getCustomers(): Promise<Customer> {
...
return await this.authRequest(someRequest);
}
private async authorisedRequest(request) : Promise<any> {
const [token, token_secret] = await this.oauth.getTokens();
if (!token || !token_secret) {
throw 'Tokens not available';
}
return await this.apiRequest(request);
}
private async apiRequest(request) : Promise<any> {
const httpRequest = ...;
// Here we are converting our Observable to a Promise to avoid mixing
return await this.http.request(httpRequest)
.toPromise();
}
}
export class AuthenticationService {
public async checkAuth() {
try {
await this.api.getCustomer();
this.isLoggedIn = true;
} catch {
this.isLoggedIn = false;
}
}
}
您还可以对converting promise to observable和Observable
使用{{1}}的方法(通常,代码与带有promise的示例相似,因此我将其跳过)