Testing if a method returns a promise

In angularjs, while checking the service, I want to check if the returned object is a promise.

Now I am doing the following -

 obj.testMethod()
        .should.be.instanceOf($q.defer());
+4
source share
4 answers

Looking at line 248 in the source for $ q ( https://github.com/angular/angular.js/blob/master/src/ng/q.js#L248 ), you really can't check what you can do it is definitely. It will be your best choice.

var deferred = method();

if(angular.isObject(deferred) && 
   angular.isObject(deferred.promise) && 
   deferred.promise.then instanceof Function && 
   deferred.promise["catch"] instanceof Function && 
   deferred.promise["finally"] instanceof Function){
   //This is a simple Promise
}

, new Promise(), promise instanceof Promise, , , , , .

"HttpPromise", error success, $http (https://github.com/angular/angular.js/blob/master/src/ng/http.js#L726):

var promise = $http(...);

if(angular.isObject(promise) && 
   promise.then instanceof Function && 
   promise["catch"] instanceof Function && 
   promise["finally"] instanceof Function && 
   promise.error instanceof Function && 
   promise.success instanceof Function){
   //This is a HttpPromise
}

EXTRA

, $HTTP deferred, , , $q.when(...) , . , $q.when deferred, $q.deferred().promise, $http(...) $q.deferred()

, , , , :

TypeError: Expecting a function in instanceof check, but got #<Object>

+8

, , :

return !!obj.then && typeof obj.then === 'function';

. then, .

, angular $q , promises.

+12

$http - , . , .

0
source

I worked with callbacks, I needed a CTA for the click event to call the function and determine what type of callback was fired, here are some simple examples.

let fn = function () { alert('A simple function') };

let cta = fn();

console.log(cta instanceof Promise);

// logs false

New Promise Example

let fn = function () {

    return new Promise(function (accept, reject) {

        accept();

        // reject();

    });

};

let cta = fn();

if(cta instanceof Promise) {

    cta.then(function () {

        alert('I was a promise');

    });

}

Axios Example 1

let fn = function () {

   return axios.get('/user');

}

let cta = fn();

if(cta instanceof Promise) {

    cta.then(function () {

        alert('I was a promise from axios');

    });

}

// Triggers alert('I was a promise from axios');

Axios Example 2

let fn = function () {

   return axios.get('/user').then(response => {
       console.log('user response', response.data);
   });

}

let cta = fn();

if(cta instanceof Promise) {

    cta.finally(function () {

        alert('I was a final promise from axios');

    });

}

// Triggers alert('I was a final promise from axios');
0
source

Source: https://habr.com/ru/post/1536559/


All Articles