首页 > 解决方案 > Angular 4异步等待承诺中未捕获的异常

问题描述

我总是收到错误消息

ERROR 错误:未捕获(承诺中):e: {"headers":{"normalize dNames":{},"lazyUpdate":null},"status":400,"statusText":"Bad Request"

代码是:(更新)

async verify() {
  let schema = {"token": localStorage.getItem('id_token')};
  let response: any = await this.http.post('/api-token-verify/', schema).toPromise();
  return response;
}

public async tokenAliveState() {
  console.log("1");
  let stuff = await this.verify();
  console.log("2");

  console.log("Returning from tokenAliveState");
  return tokenNotExpired('id_token');
}

我想做的就是发一个帖子,等待回复,然后再继续。响应是纯 JSON。

角芯 4。

有任何想法吗?需要更多信息吗?

有没有人有一个简单函数的工作示例,可以在继续执行之前等待 http 响应?我在网上找到的所有示例都与此类似,但无论我做什么,我都会得到未捕获的异常。

标签: angular

解决方案


您应该始终将 await 调用包装在 try catch 块中,然后相应地处理它。

try {
    let response: any = await this.http.post('/api-token-verify/', schema).toPromise();
} catch (err) {
    // Handle the 400 http code here.
}

推荐阅读