Reputation:
Or at least, that's what I'm thinking is happening. I have the following function:
function checkExistingMember() {
var confirmPopup = $ionicPopup.confirm({
title: 'Existing Member?',
template: 'Are you an existing member?',
cancelText: 'No',
okText: 'Yes'
});
confirmPopup.then(function(res) {
if(res) {
// User is existing member
return true;
} else {
// User is NOT existing member
return false;
}
});
} // END checkExistingMember
I then call it it at the very top of my controller like so:
var isExistingMember = checkExistingMember();
if (isExistingMember) {
console.log('Is existing member');
} else {
console.log('Is NOT existing member');
}
But then right when it's called the console prints out Is NOT existing member
before the user has had a chance to answer. Anyone know why this is happening?
Worth mentioning that if I call var confirmPopup = $ionicPopup.confirm() { ...}
and confirmPopup.then(...)
directly in my controller i.e. if I don't abstract it into a function, then everything works fine.
Upvotes: 1
Views: 204
Reputation: 193271
You need to understand that you can't just return from asynchronous code. Instead you need to return a promise object
function checkExistingMember() {
return $ionicPopup.confirm({
title: 'Existing Member?',
template: 'Are you an existing member?',
cancelText: 'No',
okText: 'Yes'
})
.then(function(res) {
if (res) {
// User is existing member
return true;
} else {
// User is NOT existing member
return false;
}
});
}
and use its chainable api:
checkExistingMember().then(function(isExistingMember) {
if (isExistingMember) {
console.log('Is existing member');
} else {
console.log('Is NOT existing member');
}
});
Upvotes: 1