Kabachok
Kabachok

Reputation: 603

How to handle functions that do not always return a promise?

What is the best way to handle situations when a function does not always return a promise? My actual code is too complicated to explain but the essence of the problem boils down to checking a condition and depending on it I either return a local variable or need to send an ajax request. Something like this:

function example(value){
   if(!value){
      return $http.get('www.example.com'); 
  }
   else {
      return "Your value is "+value; 
  }
}

Is there a way to check if the value returned by the function is a promise and needs to be resolved? Or maybe there is another approach to handle such situations? Thank you for your input!

Upvotes: 0

Views: 108

Answers (2)

samanime
samanime

Reputation: 26537

While you can test to see if the return type is a Promise: myValue instanceof Promise, it is better to simply write functions that always return a Promise. That makes them consistent and much easier to deal with. In your example where you may need to return a Promise for an async function, or may need to return a value, just use Promise.resolve() with the value:

function example(value) {
  if(!value) {
    return $http.get('www.example.com');
  } else {
    return Promise.resolve('Your value is ' + value);
  }
}

That way, you don't have to worry about what it gives back and can always deal with it in a consistent way.

Upvotes: 3

YD1m
YD1m

Reputation: 5895

You can return a promise always:

function example(value){
   if(!value){
      return $http.get('www.example.com'); 
   }
   else {   
      return $q.when("Your value is "+value); 
   }
}

Upvotes: 2

Related Questions