pablito94
pablito94

Reputation: 63

calling a function that may or may not make an http request

i have function that looks something like this..

myFunction() {
  //some logic
  if (expression) {
    return value;
  }

  Observable.forkJoin(
    service.someHttpGet,
    service.anotherHttpGet
  ).subscribe((data) => {
    //some logic
    return value;
  });
}

notice that, if the expression is true, the function will return a value right away. otherwise, there may be some delay in the return. so when i write

const x=myFunction();

x will have data if expression is true, but will be undefined otherwise. i need to be able to call this function and await in case the result is delayed. how do i do so?

Upvotes: 1

Views: 54

Answers (1)

ggradnig
ggradnig

Reputation: 14189

If your function return value depends on an at least one Observable, the return type of the function needs to be Observable or at least Promise as well. This changes the usage of the function of course, but there is no alternative to that.

You can read more about basic JavaScript callbacks here.

Your code would be modified to:

myFunction(): Observable<any> {
  if (expression) {
    return Observable.of(value);
  }

  return Observable.forkJoin(
    service.someHttpGet,
    service.anotherHttpGet
  ).pipe(
      map(values => //here you'll modify the values and return the result)
  );
}

And on usage:

myFunction().subscribe(val => x = val);

Upvotes: 3

Related Questions