首页 > 解决方案 > 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,所以如果有人对可能缺少的内容有任何想法,将不胜感激。

标签: angularasynchronousasync-await

解决方案


Lexith 添加的评论有帮助:-)

await this.setJwtToken();会给你你预期的输出。


推荐阅读