首页 > 解决方案 > 等到等待/异步在 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 中执行任何其他操作之前发生此设置值。

寻求帮助

标签: javascriptjqueryasynchronous

解决方案


问题是它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
}

推荐阅读