I wrote an API which gets called by multiple clients and computes their request. It roughly look like this:
async function main(request){
url = //extractUrlFromRequest
answer = await compute(url)
}
async function compute(url){
answer = await fetch(url)
//other computations
return answer
}
Keep in mind that the main function can be called multiple times per second or even at the same time by different clients and the computation time of the compute function may vary per request (up to ~2 seconds).
The Problem
The problem is that if a compute() call isn't finished before the next compute() call arrives the fetch() of the second call will override the fetch() of the first call no matter where in the code it currently is (The parameters in the header i.e. url do not change).
Example - Expected behavior
compute() gets called the first time -> fetch() returns "hello"
-> continues computationcompute() gets called the second time -> fetch() returns "world"
-> continues computationcompute() finishes -> returns "hello"compute() finishes -> returns "world"Example - Observed behavior
compute() gets called the first time -> fetch() returns "hello"
-> continues computationcompute() gets called the second time -> fetch() returns "world" and replaces "hello" of the first call with "world"
-> continues computationcompute() finishes -> returns "world"compute() finishes -> returns "world"What can i do to achieve the expected behavior?
What i've tried
I have read on MDN that Promise.all can be used to run multiple promises / awaits at once, however this isnt exactly my usecase since i dont have every request at the beginning, but they rather come in one after another and call the main() function again.
I've read that javascript is fundamentally single-threaded / linear, is it even possible to achieve the expected results, or did i choose the wrong language for this project?