Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Attaching a promise to another result

I am working with two promises and have simplified this to make things easier to look at.

Note Cars and ServiceRecords are 2 different tables.

I would like my end dataset to look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

car = {
make: Honda,
color:red,
id:12,
serviceRecords:[
      {type: oil change,
       customerHappy: Yes,
       id:1
       carid:12
       },
      {type: oil change,
       customerHappy: no
       id:2
       carid:12
       }
     ]
}

First Promise

getCar() {
    return new Promise((resolve, reject) => {
      const id = this.route.snapshot.paramMap.get('id');
      // find the car we want
      const car = Xrm.WebApi.retrieveRecord('car', `${id}`);
      if (car ) {
        resolve(car ); // send the car
      } else {
        reject(Error('No Car Found!'));
      }
    });
  }

Second Promise

hydrateCar(car) {
    return new Promise((resolve, reject) => {
      const services:any = Xrm.WebApi.retrieveMultipleRecords('servicerecord', `?$filter=carid eq ${car.id}`).then((results) => {
        for (let i = 0; i < results.entities.length; i++) {
          const result = results.entities[i];
           car.serviceRecords=result;
        }
        resolve(car);
      });
    });
  }

Call the function

this.getCar().then((car) => {
      console.log('car', car);
      return this.hydrateCar(car);
    })
      .catch((error) => {
        console.log(error);
      });
    this.loading = false;
  }

All I get back is the last iteration of the service record. I would like the key car.ServiceRecords to be an array of all the records.

>Solution :

hydrateCar(car) {
  return new Promise((resolve, reject) => {
    Xrm.WebApi.retrieveMultipleRecords('servicerecord', `?$filter=carid eq ${car.id}`).then((results) => {
      const serviceRecords = []; 
      
      for (let i = 0; i < results.entities.length; i++) {
        const result = results.entities[i];
        serviceRecords.push(result); 
      }
      
      car.serviceRecords = serviceRecords;
      resolve(car);
    });
  });
}

The issue you’re facing is that you’re overwriting the car.serviceRecords property in each iteration of your loop in the hydrateCar function. Instead, you should accumulate the service records into an array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading