A
A
Artem2019-03-23 19:46:52
JavaScript
Artem, 2019-03-23 19:46:52

How to change the same array at the same time in Node.js?

Problem with concurrent requests.
There is a server on a node, web sockets are used as transport.
There is this code:

let product = this.products.find(item => item.code == data.code);
    if (product) {
      product.count = data.count;
    } else {
      await this.pushProduct(data.code, data.count);
    }

In pushProduct, a request is made to the database, an async function, a request via await. Something like this (error handlers cut out):
const res = await models.product.getByCode(code);
res.count = count;
this.products.push(res);

The logic is to have the this.products array contain elements with a unique code key, i.e. they should not be duplicated. If there is an element with this code, then just change its quantity.
So, if you pull 5 requests in a row at once, then 5 identical elements will be added. If these requests are performed at intervals per second - one element.
How to solve such a problem / what to read? Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem, 2019-03-23
@ber_enot

Solved the problem with the async-lock library .

S
Stockholm Syndrome, 2019-03-23
@StockholmSyndrome

if there is already an element with this code, then just don't add it

if (!this.products.find((item) => res.code === item.code)) {
  this.products.push(res);
}

Or I didn't understand the question

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question