1

So I am creating a service which sends a message to the backend to check whether a particular email address is already on the database.

userDB.emailExists = function()
{

    var returnVal;

    $http.get('?backend=users&email=myemail%40mydomain.com')
         .success(function(data) { returnVal = data.count ? true : false; })
         .error(function(data) { /* TODO error handling */ });

        returnVal = data.count ? true : false;
    });

    return returnVal;
};

Now currently the unit test for this (testing to see whether the function returns true or false) is failing with Expected undefined to be truthy.. I think I get why; as a promise only returns a 'placeholder' so at the time we get to the 'return' statement, returnVal has not been set yet.

Only problem is, I don't know how to fix this; I don't want to return the promise as this seems an unnecessary layer of complexity when the result is a simple true or false

Ben Wainwright
  • 4,224
  • 1
  • 18
  • 36
  • You can'd do that since you are making an async call.... to see how to handle it - http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Arun P Johny May 04 '15 at 08:48

1 Answers1

3

Only problem is, I don't know how to fix this; I don't want to return the promise as this seems an unnecessary layer of complexity when the result is a simple true or false

You have to return the promise (or take a callback) - this is simply how coding is done in async i.o in Angular and in browser JavaScript in general. See this question for the conceptual explanation.

Conceptually the complexity you speak of is already there since your function conceptually doesn't return true/false, it performs a network request and returns true/false based on its result.

You should however - return a promise for the true/false value and not the $http request:

userDB.emailExists = function() {
    return $http.get('?backend=users&email=myemail%40mydomain.com')
         .then(function(r) { return Boolean(r.data.count); });
};
Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504