【发布时间】:2021-07-01 12:39:39
【问题描述】:
我有多个异步调用。比如四个
this.lazyLoadData();
this.lazyLoadData();
this.lazyLoadData();
this.lazyLoadData();
问题是每个 http 请求可能需要不同的时间。 在每个请求中,我都会发送不同的查询参数以在后端获取分页数据。
所以在这种情况下,第一个 this.lazyLoadData 有时可能会晚于第二个 -
取决于后端的分页结果。
为了防止这种行为,我尝试使用async and await
await this.lazyLoadData();
await this.lazyLoadData();
await this.lazyLoadData();
await this.lazyLoadData();
async lazyLoadData(cb?) {
const filtersParam: any = {
page: this.filterService.dashboardPage,
size: 25,
}
let response = await this.processMonitorService.monitoring(filtersParam);
response.then(data => {
console.log('maked http call');
});
...
}
但问题是,即使我使用 async 和 await - 这四个 http 调用并没有按顺序发生。
所以在一秒钟的时间内我调用了四次lazyLoadData,我在那里等待每个结果
但响应不按顺序排列。所以有时第三个会在第二个之前执行,等等......
我该如何解决这个问题?
【问题讨论】:
-
stackoverflow.com/questions/45285129/… 使用 promise.all ?
-
console.log('maked http call');到底发生了什么?如果你在那里有另一个承诺,那么你应该返回它。无论如何,你应该await打一个then电话。 -
this.processMonitorService.monitoring是做什么的?你确定它返回一个承诺,如果是,它会在 HTTP 调用收到响应时解决吗? -
它返回 Observable,我需要转换它 - this.processMonitorService.monitoring.toPromise() 所以 await 可以工作
标签: javascript asynchronous async-await