我开始更多地使用 async wait
模式而不是标准 Promise 语法,因为它可以使代码更加扁平。我已经玩过并尝试过它们,并且认为我了解如何使用它们。
现在已经崩溃了!
我有一个返回 Promise 的函数...
private async checkSecurityTokenForNearExpiry(): Promise<boolean> {
const expiryOffset = 10;
try {
let existingToken = await this.userAuthorisationService.getSecurityToken();
if (existingToken != null && !existingToken.isTokenExpired(expiryOffset)) {
return true;
}
// Attempt to get a new token.
this.logger.debug('checkSecurityTokenForNearExpiry requesting new token.');
this.getSecurityTokenWithRefreshToken().subscribe(obs => {
return true;
},
error => {
// All errors already logged
return false;
});
} catch (error) {
this.logger.error(`checkSecurityToken ${error}`);
return false;
}
}
这恰好调用了其他返回 Promise 的函数,并且也有 Observable,但这一切似乎都没问题。
然后我按如下方式调用该函数...
this.getDataStoreValues().then(async () => {
await this.checkSecurityTokenForNearExpiry(); // <-- not waiting
requestData(); // <-- this is called before checkSecurityTokenForNearExpiry returns
...
这是在另一个 Promise then
回调中标记为 async
(这应该没问题?),但令我震惊的是对 this.checkSecurityTokenForNearExpiry(在我看到
尚未完成。我不需要 requestData()
被调用之前, )checkSecurityTokenForNearExpiry
的 boolean
结果,但添加它只是为了看看返回某些内容是否会有所不同,但事实并非如此。
我在这里迷路了!
有人知道我在这里缺少什么吗?
提前致谢!
最佳答案
async
/await
正在按预期工作,但有两个因素会阻止您的代码正常工作。
Observables 与异步函数没有特殊的交互。这意味着它们就像正常功能一样,一劳永逸。您没有等待
getSecurityTokenWithRefreshToken
但即使您确实await
它,它仍然不会按照您想要的方式运行,因为结果实际上是调用返回的订阅>subscribe
包裹在Promise
中。subscribe
作为参数的回调并不打算返回值,因此从它们返回没有任何效果,因为Observable
实现不会传播其结果。
为了完成这项工作,您需要将 Observable
转换为 Promise
,如下所示
async checkSecurityTokenForNearExpiry(): Promise<boolean> {
const expiryOffset = 10;
try {
let existingToken = await this.userAuthorisationService().getSecurityToken();
if (existingToken != null && !existingToken.isTokenExpired(expiryOffset)) {
return true;
}
// Attempt to get a new token.
this.logger.debug('checkSecurityTokenForNearExpiry requesting new token.');
try {
await this.getSecurityTokenWithRefreshToken().toPromise();
return true;
} catch (error) {
return false;
}
} catch (error) {
this.logger.error(`checkSecurityToken ${error}`);
return false;
}
}
注意,如果您使用 RxJS,您可能需要添加以下导入
import 'rxjs/add/operator/toPromise';
关于javascript - TypeScript async wait 似乎并不总是等待 ("block and come back"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42183305/