Remix.run Logo
arctek 8 months ago

I actually think out of any language async/await makes the most sense for javascript.

In the first example: there is no such thing as a blocking sleep in javascript. What people use as sleep is just a promise wrapper around a setTimeout call. setTimeout has always created microtasks, so calling a sleep inline would do nothing to halt execution.

I do agree that dangling Promises are annoying and Promise.race is especially bad as it doesn't do what you expect: finish the fastest promise and cancel the other. It will actually eventually resolve both but you will only get one result.

Realistically in JS you write your long running async functions to take an AbortController wrapper that also provides a sleep function, then in your outer loop you check the signal isn't aborted and the wrapper class also handles calling clearTimeout on wrapped sleep functions to stop sleeping/pending setTimeouts and exit your loop/function.

tempodox 7 months ago | parent | next [-]

> async/await makes the most sense for javascript.

More like: Has no alternative. There are no threads in JS.

threadthis 7 months ago | parent | next [-]

Yes there are. They are called "Workers" (WebWorkers), though. It's a semantic game with a different API but the same concept.

https://www.w3.org/TR/2021/NOTE-workers-20210128/

com2kid 7 months ago | parent | prev [-]

Note that the underlying C++ libraries for Node are perfectly capable of using threads, only the final user space model is single threaded by default.

mst 7 months ago | parent | prev | next [-]

I rather like things like the mobx flow action system based on generators - you yield() promises rather than awaiting them and use yield* to splice other functions following the same approach.

You can see a nice example of using that approach standalone here: https://axisofeval.blogspot.com/2024/05/delimited-generators...

huem0n 7 months ago | parent | prev [-]

_

    function blockingSleep(amt) {
        let start = new Date().getTime()
        while (start + amt > new Date().getTime()) {}

    }
arctek 7 months ago | parent [-]

This is horrible - I love it.

I did forget you could do this, though I'm fairly sure in the case of a browser (at least it used to) this will block the entire UI.