'How do I send data to server by loop without sync problem?

I have an array of products in typescript (in angular) and I need to update their prices in the database via http calls.

I insert them in such a way:

array.foreach(element=>{
   this.product.price=element;
   this.myService.func(this.product).subscribe(a=>{console.log(a);});
})

The problem with this code is that the That the final data is incorrect because the answers from the server come slower, so if for example there were 3 objects in the array - then for the last two will send to the server the same price, of the last member of the array.

More clear example:

Assume the array is initialized to these prices:

[0]=10
[1]=20
[2]=30

Except for that array, I have a product:

Product p = new Product('product',50);

Now I want to insert to the database 3 more products with the name 'product' and the prices from the array. Thst will be via the function from the server.

The outcome I want is all the products that were inserted to the database

product,10
product,20
product,30

But instead of this I get this outcome:

product,10
product,30
product,30

How can I fix it?

Thanks a lot.



Solution 1:[1]

  1. The requests are not necessarily ran sequentially, you can use an operator such as concat:
concat(array.map(element=>{
    this.product.price=element;
    return this.myService.func(product)
})).subscribe(a=>{console.log(a);});
  1. On each iteration you are updating the same instance of the product (if that's not intentional) which has caused strange behavior.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hamidreza Vakilian