#a native alternative to MaybePromise?

8 messages · Page 1 of 1 (latest)

zealous cave
#

one thing I find myself using a lot is MaybePromise<T> = Promise<T> | T

this is because in some environments when i specify a function it doesn't always need to be async

i've noticed in some libraries that dont use this approach, you need to add the async keyword to your function even if you dont need the callback you're providing to be async - which seems wrong and messy

is there another approach that doesnt require me to come up with this utility type? something a little more blessed by the typescript gods?

eager sentinel
#

you need to add the async keyword to your function even if you dont need the callback you're providing to be async - which seems wrong and messy
i dont really see anything wrong with doing this

#

typescript eslint has a rule that complains about async functions that don't contain "await" or return a promise
https://typescript-eslint.io/rules/require-await
which is annoying in cases where you need to pass in an async function, or you're extending a class and overriding an async function

#

i think its a dumb rule so i turn it off

tame herald
#

@zealous cave can you show some examples of how you use MaybePromise?

languid osprey
# tame herald <@235569562634944515> can you show some examples of how you use `MaybePromise`?

I believe he is looking for a "lazy Promise".

Promises are "eager", so even if there is no await, they will be executed and the resolved value is stored, which anyone can access by using await/then().

I think he could just solve his problem by wrapping the Promise around a function, that he call, whenver he needs that promise to be resolved aka. an async function.

If the truely needs a "lazy promise" then he should look into Observables, because Obeservables are not "eager" but "lazy" by design which menas they are only run, when somebody subscribed them (plus they can be canceled).

languid osprey
#

@olive flower To address your ❓

I guess the easiest way to understand is to check out the differences between Observable and Promise focusing how they (eagerly/lazy) resolve a value.

Obviously Observables serve a different purpose

E.g. (simplified, not valid code)


new Promise(()=> 'im executed eagerly')

new Observable(()=>'i wont do nuffin until someone subscribes me')
olive flower
#

@languid osprey I know what Observables are - but I don't really think that's what OP was asking about.