javascript - 等到等待/异步在 Jquery 中返回
问题描述
我是 Jquery 中的 await/async 新手。当我尝试在我的 js 文件中使用它时,它正在执行,但没有按预期进行。
async updateProduct (product) {
product.travelers.forEach((traveler, travelerOrder) => this.updateProductwithPassengerName(traveler) )
return product
}
async updateProductwithPassengerName (traveler) {
const travelerId = traveler.profile_id;
var body = await this.userServiceClient.request('/v2/users/' + travelerId + '/info','GET')
traveler.first_name = body.first_name
traveler.last_name = body.last_name
return traveler
}
async request (path, method, body) {
const options = {
method: method,
body: body,
headers: this.headers(),
credentials: 'same-origin'
}
const response = await fetch(this.relativeUrl(path), options)
if (!response.ok) {
throw new HttpError('Technical error occured', response.status)
}
return response.json().catch(function () {
throw new HttpError('No results found', response.status)
})
}
这是3个功能。现在发生的事情是
traveler.first_name = body.first_name
traveler.last_name = body.last_name
这些不是以同步方式设置的(之后
var body = await this.userServiceClient.request('/v2/users/' + travelerId + '/info','GET')
. 这些都是在安静了很长一段时间后执行的。
我在这里所做的是,我为每个旅行者设置名字和姓氏。并更新产品对象。由于这种值的设置是在很长一段时间后发生的,因此产品对象会在稍后更新 UI 页面时。我希望在 jquery 中执行任何其他操作之前发生此设置值。
寻求帮助
解决方案
问题是它forEach
不会等待异步结果,因此您的第一个函数返回一个立即解决的承诺,而无需等待请求完成。
以下是如何纠正:
async updateProduct (product) {
await Promise.all(product.travelers.map((traveler, travelerOrder) => this.updateProductwithPassengerName(traveler) ));
return product
}
或者,如果主干无法处理所有这些并发请求,则等待每个请求完成后再发出下一个:
async updateProduct (product) {
for (let traveler of product.travelers) {
await this.updateProductwithPassengerName(traveler);
}
return product
}
推荐阅读
- javascript - 如何将部分视图加载到 Bootstrap 4 模式中
- kotlin - 使用 'body(): ResponseBody?' 出现错误 是一个错误。使用 okhttp 移至 val
- javascript - 通过其元素的出现有效地对数组进行排序
- typo3 - 在 TYPO3 中添加自定义内容元素布局
- kotlin - “重复”属性名称的kotlin命名约定?
- php - 为什么我的 PHP WSDL (Zf2) 中没有返回成功
- javascript - 平滑滚动某些标签而不是其他标签?
- java - 即使将交互模式设置为 True,Z3 也会失败
- angular - 如何选中复选框检查循环值是否以角度为真
- python - 删除 PyCharm 和所有相关目录