提问人:DSmith 提问时间:10/8/2023 最后编辑:Darryl NoakesDSmith 更新时间:10/8/2023 访问量:48
将承诺附加到另一个结果
Attaching a promise to another result
问:
我正在处理两个承诺,并简化了这一点,使事情更容易看。
注意:Cars 和 ServiceRecords 是 2 个不同的表。
我希望我的最终数据集看起来像这样:
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
}
]
}
第一个承诺
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!'));
}
});
}
第二个承诺
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);
});
});
}
调用函数
this.getCar().then((car) => {
console.log('car', car);
return this.hydrateCar(car);
})
.catch((error) => {
console.log(error);
});
this.loading = false;
}
我得到的只是服务记录的最后一次迭代。我想要钥匙车。ServiceRecords 是所有记录的数组。
答:
0赞
VOZ ESTOICA
10/8/2023
#1
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);
});
});
}
您面临的问题是,在 hydrateCar 函数中循环的每次迭代中都覆盖了 car.serviceRecords 属性。相反,您应该将服务记录累积到数组中。
评论
Promise
构造函数反模式!console.log('car', car);
new Promise()
hydrateCar
getCar