lito lito - 2 years ago 103
Javascript Question

how to resolve a $q for promise?

I'm using AngularJS and $q for promises, I'm confuse with the usage, How can I fix this promise?

I want to return the user when isLoggedInPromise() is called or a "AUTH_REQUIRED".


function isLoggedInPromise() {
$q.when(userWithAllData()).then(function(user) {
return user;
$q.when(userWithAllData()).reject(function() {

function userWithAllData(){
var deferral = $q.defer();

var query = new Parse.Query(Parse.User);
query.include(["info", "info.rank", "privateInfo"]);
query.get(Parse.User.current().id).then(function (loadedUser){
deferral.resolve( loadedUser );

return deferral.promise;

Answer Source

What you want to do is call the resolve function on the promise when the function has all the data it needs to actually return

in a function that returns a promise, think of "resolve" as the actual return statement.

so your isLoggedInPromise function needs to return a promise as well which will kind of make it redundant. Anything that needs a user will have to wait for it via then.

isLoggedInPromise().then(function(result){...etc...}, function(reason){//auth needed})

If you still need the isLoggedin Function then it should look like

 function isLoggedInPromise() {
    var isLoggedIn = userWithAllData().then(
        function(user) {
            return user;
            return $q.reject("AUTH_REQUIRED")

of course you'll have to include some rejection logic in the userWithAllData function as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download