I am looking to implement a job queue that ensures the response from an API is returned in the order of input items entered even in spite of each API call taking a variable amount of time potentially.
See codesandbox here https://codesandbox.io/s/sequential-api-response-eopue - When I input item
such as 1, 12, 1234, 12345 in the input field and hit Enter, it goes to a simulated backend where I return item
+-response
to signify the output of corresponding input. However, I have used a different timeout on each call using Math.random()
to simulate a real-world scenario where the API could take a non-deterministic amount of time.
Current output
processing: 1
processing: 12
processing: 123
processing: 1234
processing: 12345
processing: 123456
response: 1234-response
response: 12-response
response: 123456-response
response: 123-response
response: 1-response
response: 12345-response
Expected output The output I'd like to see is
processing: 1
processing: 12
processing: 123
processing: 1234
processing: 12345
processing: 123456
response: 1-response
response: 12-response
response: 123-response
response: 1234-response
response: 12345-response
response: 123456-response
My attempt:
I have tried to implement the function getSequentialResponse
(which is a wrapper over the function getNonSequentialResponse
that generates the incorrect output above). This function adds the item
that the user enters to a queue
and does queue.shift()
only when the lock variable _isBusy
is released by getNonSequentialResponse
indicating that the current promise has resolved and its ready to process the next. Until then, it waits in a while
loop while the current item is being processed. My thinking was that since elements are always removed the head, the items will be processed in the order in which they were input.
Error: However, this, as I understood is the wrong approach since the UI thread is waiting and results in the error Potential infinite loop: exceeded 10001 iterations. You can disable this check by creating a sandbox.config.json file.