O
O
OcelotJungle2021-02-02 19:40:50
JavaScript
OcelotJungle, 2021-02-02 19:40:50

What is the correct way to use fetch with promises and locks?

There is a class that provides static methods getEventList and getEventDetails. The first one does a fetch to the server in order to get a list containing basic information about the events (events). The second one also does a fetch to the server, but in order to get detailed information about a particular event.
In this case, the received information should be cached. That is, for example, first I call getEventList and the list of events is written to the static variable events (array of objects). Then, if I call getEventDetails, the received information about the event should supplement the information already available, and no further request to the server should be made.
However, there is no guarantee that getEventList will be called and return a result before getEventDetails is called. In other words, when calling getEventDetails, it should also check if there is a list of events at all, and if not, then load it. But at this point, the getEventDetails function could be called from somewhere else, resulting in the list being downloaded twice, which also leads to unpredictable code behavior. I came to the conclusion that at the time of loading the list, you need to set a flag that informs about this, and in case of an attempt to start reloading (again, for example, while the first one has not yet completed, and the list has already been required), just wait for the first call to complete its work . How to wait? setInterval? Promises?

I apologize if I didn’t write very clearly, but I already have such a mess in my head about this that I can’t even clearly formulate the question. If someone can tell me how to organize it all correctly - I would be grateful.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Cheremkhin, 2021-02-02
@Che603000

Promises are clear. )
https://learn.javascript.ru/promise

L
Lynn "Coffee Man", 2021-02-03
@Lynn

Still, it is not very clearly described what a static variable is.
But in general, in this case, I would store not an object in events, but a promise, and in the call to getEventList I would check that if the variable exists, then there is no need to go anywhere.

let events = null;

function getEventList() {
    if (events) return events;
    events = fetch(...).then(r => r.json());
    return events;
}

async function getEventDetails() {
    events = await getEventList();
    // ...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question