Any way to know if a variable is an angularjs promise?

Angularjs

Angularjs Problem Overview


I'm making a directive that takes a function as a scope parameter (scope: { method:'&theFunction' }). I need to know if the result returned by that method is an angular promise (if yes something will happen on resolution, otherwise it happens right away).

For now I'm testing if foo.then exists but I was wondering if there was a better way to do it.

Angularjs Solutions


Solution 1 - Angularjs

You can use $q.when to wrap the object as a promise (whether it is or not). Then, you can be sure that you are always dealing with a promise. This should simplify the code that then handles the result.

Documentation for $q.when is here with $q.

Solution 2 - Angularjs

Angular's when() is a good option as Davin mentioned.

If that doesn't meet your needs then Angular's internal way of checking (it uses this inside when) is very close to what you're doing:

var ref = function(value) {
   if (value && isFunction(value.then)) {
      // Then this is promise
   }

Solution 3 - Angularjs

@kayakDave, thanks for guiding to right place.

angular $q

> when(value, [successCallback], [errorCallback], [progressCallback]); Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

$q.when(value).then(function (data) {
//this helps me to bind data from $resource or $http or object
}

check this fiddle

Solution 4 - Angularjs

The $q.when() answer seems like the best answer for most use cases, I used instanceof for mine.

    if(buttonData instanceof $q) {
        buttonData.then(function(actions) {
            $scope.buttonActions = actions;
        });
    } else {
        $scope.button = buttonData;
    }

Alternatively, the following IF worked as well, but I ended up going with the above solution.

if(Object.getPrototypeOf(buttonData) === $q.prototype) {

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSebastien F.View Question on Stackoverflow
Solution 1 - AngularjsDavin TryonView Answer on Stackoverflow
Solution 2 - AngularjsKayakDaveView Answer on Stackoverflow
Solution 3 - AngularjsSajjad Ali KhanView Answer on Stackoverflow
Solution 4 - AngularjsGabe GatesView Answer on Stackoverflow