top | item 44484104

(no title)

ncann | 7 months ago

> Here's a naive, faulty implementation

For this first implementation, I don't see anything ever added to the queue. Am I missing something? New task is added to the queue if the queue is not empty only, but when the queue is empty the task is executed and the queue remains empty so in the end the queue is always empty?

discuss

order

63stack|7 months ago

Another thing is that the article emphasized that it's single threaded. That by itself guarantees that there will only ever be 1 inflight request, since calling the send() function will block until the request completes, and the callback is called.

If there is some kind of cooperative multitasking going on, then it should be noted in the pseudo code with eg. async/await or equivalent keywords. As the code is, send() never gives back control to the calling code, until it completely finishes.

_benton|7 months ago

JS has an event loop, it's single threaded but still lets you write asynchronous code.

let send = (payload, callback) => fetch(...).then(callback)

fetch() returns a promise synchronously, but it's not awaited.

gpderetta|7 months ago

it is too abstract to say for sure, but send might just block until the request is handled off to the next layer (for example succesfully written to the OS network socket buffer), so unless the server carefully closes its recv window until it is done handling the request[1] , no, I wouldn't expect send to block until the server is done handling the request.

[1] i.e. backpressure, which would actually be the ideal way for the server to implement whatever rate limiting it wants, but we are assuming here that the server has a less than ideal interface.

rehevkor5|7 months ago

Yeah that confused me at first too. They seem to be treating send() as if it has the same behavior as a setTimeout() call. If you think of it that way, it starts to make sense.

ethan_smith|7 months ago

You're absolutely right - the naive implementation has a logical flaw where the queue would always remain empty since tasks are only added when the queue is non-empty, creating a catch-22 situation where the queue can never grow.

JohnKemeny|7 months ago

That's how I read it too. Nothing is ever added.

Arch-TK|7 months ago

That's correct.