angular - Angular 5 async-await 未按预期等待
问题描述
我需要在 Angular 5 中创建一个“同步”http 调用。鉴于以下代码片段:
console.log("1) Before async-await call");
this.setJwtToken();
console.log("3) After async-await call");
和
async setJwtToken(): Promise<any> {
var result = await this.http.get<any>(URL,{}).toPromise();
console.log("2) getJwtToken complete: ", result);
return result;
}
我希望我的控制台日志消息打印如下:
1) 在 async-await 调用之前 2) getJwtToken 完成:“result here” 3) 在 async-await 调用之前
但我得到的命令是:
1) 在 async-await 调用之前 3) 在 async-await 调用之前 2) getJwtToken 完成:“result here”
我有点不知所措,为什么代码没有等待 http 调用完成后再继续。这是我第一次尝试在 Angular 中使用 async-await,所以如果有人对可能缺少的内容有任何想法,将不胜感激。
解决方案
Lexith 添加的评论有帮助:-)
await this.setJwtToken();
会给你你预期的输出。
推荐阅读
- javascript - React 和 Liferay 门户路由的区别
- amazon-web-services - 在分隔符之前创建带有转义字符的 Athena 表
- firebase - firebase bool 传递给 null 错误
- gradle - 如何在 Gradle 构建文件中正确排除“junit-vintage-engine”?
- sql-server - 如何使用 sp_send_dbmail 发送表 - sql server
- c++ - 如何在精神上解析字符串并将其用作返回值
- .net - .NET:如何将 Azure RetriableStreamImpl 转换为 ASP.Net Core IFormFile?
- ios - 带有开放式 cv 和 tensorflow 的自定义 agora sdk 颤振
- java - InsufficientAuthenticationException 的 Spring Boot 自定义错误对象
- python - 如何通过端口转发让我的朋友可以使用 Flask 应用程序?