Jince Martin
Jince Martin

Reputation: 231

Wait till await/async returns in Jquery

I am new to await/async in Jquery. When I am trying to use it in my js file, It is getting executed, but not as expected.

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)
    })
  }

Those are the 3 functions. What is happening now is that

traveler.first_name = body.first_name
traveler.last_name = body.last_name

these are not setting in synchronous manner( after

var body = await this.userServiceClient.request('/v2/users/' + travelerId + '/info','GET')

. These are executing after a quiet a long time.

What I am doing here is that, for each traveler I am setting first_name and last_name. And updating the product object. Since this setting of values is happening after a long time, product object is getting updated later, by the time UI page renders. I want this setting values to happening before doing anything else in jquery.

Looking for help

Upvotes: 2

Views: 4026

Answers (2)

trincot
trincot

Reputation: 350097

The problem is that forEach will not await the asynchronous result and so your first function returns a promise that immediately resolves, without waiting for the requests to finish.

Here is how to correct:

async updateProduct (product) {
    await Promise.all(product.travelers.map((traveler, travelerOrder) => this.updateProductwithPassengerName(traveler) ));
    return product
}

Or, if the backbone cannot deal with all these concurrent requests, then wait for each of them to complete before issuing the next:

async updateProduct (product) {
    for (let traveler of product.travelers) {
        await this.updateProductwithPassengerName(traveler);
    }
    return product
}

Upvotes: 2

Nija I Pillai
Nija I Pillai

Reputation: 1136

when using asyn/await in JQuery or angularjs or nodejs, use promise. Promise will complete the process and then return either success or fail. Then only execute next steps.Go through below links and you will get idea.

  1. Modern Asynchronous JavaScript with Async and Await
  2. async & await in Javascript

Upvotes: -1

Related Questions