Reputation: 2086
I have a question similar to this: How do I wait for a promise to finish before returning the variable of a function?
I have a function pass()
that does some form validation. As part of this, it will sometimes open a modal that the user has to close before it returns a value, like so:
if ($scope.model.validation == "No") {
$scope.modalInstance = $uibModal.open({
animation: true,
templateUrl: 'pleaseval.html',
controller: 'PleaseValCtrl',
size: 'lg'
}).closed.then(function() {
return true;
});
}
Note that it doesn't return true
until the modal closes.
However, I have a conditional based on the function's evaluation
if(pass(form))
{
//some code here
}
else{
alert("Please fill out all the required information before hitting 'Next'");
}
Because it waits for a promise (the modal to close) it returns false
and fires the alert, without waiting for the modal to close and actually firing true
.
How do I structure this code so as to not fire the alert while waiting for the modal to close?
Thank you!
Edit: I should note that I can do this:
pass(form).then(function(result){
if(result)
{
The problem with this is that if arguments are passed to pass()
that don't necessitate waiting for the modal, I get an undefined promise.
TypeError: Cannot read property 'then' of undefined
Upvotes: 0
Views: 42
Reputation: 2128
Since your edit, it sounds like pass
sometimes returns a promise. FYI, in the future, the full code of pass
would be helpful, particularly around what it returns - your posted code actually shows nothing about what pass
returns, since the "return true" isn't actually what pass
itself is returning.
You need to ensure pass always returns a promise in every code path. If the modal isn't necessary, and you have a synchronous return value, make pass
return Promise.resolve(true);
- that is, the value of true, but wrapped as a promise so the return value of pass
is always thenable. That way, the caller of pass
doesn't need to know or care whether the operation completed sychronously or asynchronously.
Upvotes: 1