R
R
Roman Rakzin2022-01-27 09:17:46
Angular
Roman Rakzin, 2022-01-27 09:17:46

Is it possible to make a function in angular / typescript that could return a Promise if it had .then or Observable called when it was subscribed?

Is it possible to make a universal function that would return a promise if .then() is launched on it or Observable if it is subscribed to or not, but is it better not to bother and write 2 different functions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twolegs, 2022-01-27
@twolegs

It is possible to write a function that always returns an Observable. If you need to get a promise - just wrap the function call in `firstValueFrom` or `lastValueFrom` from rxjs.
What you originally wrote can be solved with an extended Observable, something like (pseudocode)

class ObservableWithThen extends Observable {
  then(cb) {
    return firstValueFrom(this).then(cb);
  }
}

And in the function, instead of the usual Observable, create and return ObservableWithThen

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question