Issue
I fetch data from a server and use therefore a promise to wait till the data is arrived. Now I'm in the situation that if I go to a page and from their back to the other page, the tasks-Array, that I use to emit the customer tasks to an other component, has if I log it three SelectedCustomerTasks-Elements. But if i want to find the one element of the selected customer i only get an array with just one SelectedCustomerTasks-Element.
This is the console output of the this.customerTasks-Array in the function findTasksOfCustomer:
0: {customerId: '418', tasks: Array(1), openTasksAmount: 1}
1: {customerId: '503', tasks: Array(1), openTasksAmount: 1}
2: {customerId: '409', tasks: Array(4), openTasksAmount: 3}
and this is the console output if I iterate through this array in the function findTasksOfCustomer:
{customerId: '418', tasks: Array(1), openTasksAmount: 1}
I haven't experienced such unusual behavior and I don't know why that happens.
This is my code:
private loadTasks() {
return new Promise((resolve, reject) => {
var tasks: tasks[] = [];
this.customers.forEach(async (customer, index) => {
var tasks = (
await this._taskClient.getCustomerTasks(customer.customerId).toPromise()
).map((x) => JSON.parse(x) as Task);
var data: SelectedCustomerTasks = {
customerId: customer.customerId,
tasks: tasks,
openTasksAmount: tasks.filter(
(x) => x.output[0].valueBoolean !== true
).length,
};
tasks.push(data);
if (index == this.customers.length - 1) {
resolve(tasks);
}
});
});
}
public ngOnInit() {
this.loadTasks().then((tasks: SelectedCustomerTasks[]) => {
if (tasks.length > 0) {
this.customerTasks = tasks;
if (sessionStorage.getItem("customerId")) {
this.selectedCustomer = this.customers.find(
(x) => x.customerId == sessionStorage.getItem("customerId")
);
if (this.selectedCustomer) {
this.emitCustomerData(this.selectedCustomer, false);
}
}
}
});
}
private async emitCustomerData(customer: Customer){
this.selectedCustomerEvent.emit(this.findTasksOfCustomer(customer));
}
private findTasksOfCustomer(customer: Customer): SelectedCustomerTasks {
return this.customerTasks.find((x) => x.customerId == customer.customerId );
}
I've debugged the code.
Solution
Just to complete this question, so it can be closed:
Problem was that the resolve(tasks)
was called inside a for each loop, which means that the for loop did not need to run completely through before resolve(tasks)
was called. This was leading to an unexpected behavior depending on the order of the asynchronous tasks resolving.
Switching the approach to resolving only after all promises created by this._taskClient.getCustomerTasks(customer.customerId).toPromise()
are resolved did the trick. Here Promise.all(...)
was used to collect all promises and wait until all of them are resolved.
Answered By - Fabian Strathaus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.