0

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

Summer Developer
  • 2,056
  • 7
  • 31
  • 68
  • Can you explain why you're using a promise here? Is `pass` a long running validation backend process? If you're merely running client-side validation, sticking to a synchronous call will work. – Butifarra Jul 01 '17 at 20:09

1 Answers1

1

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.

PMV
  • 2,058
  • 1
  • 10
  • 15
  • `Promise.resolve(true);` does not fire true for the `if(result)` part... do I have to pass additional parameters? – Summer Developer Jul 01 '17 at 20:06
  • @SummerDeveloper Post the full code of `pass` - or at least every part that handles flow control (promises, if/else, return, etc). – PMV Jul 01 '17 at 20:09
  • Well it actually works, it just broke something else down the line which is confusing but outside of the scope of this question I believe. – Summer Developer Jul 01 '17 at 20:22