How to halt execution until Promise is resolved

I just started working with promises and so far they are great. However, the software I am writing at the moment requires me to collect all promises and get an aggregated result of them. This process has to finish before the code can continue executing, as the future execution depends on the result.

For a validation framework I make validation requests in the form of promises, these get stored (and are async) in an array. When I click the submit button it should await all validation promises and only execute if all promises are resolved successfully. This is done with the following code, which should return false but unfortunately returns true:

console.log(valid());

function valid() {
  // ...
  some_prev = true;
  pending = [
    new Promise(function(resolve) {
      setTimeout(function() {console.log('done resolve'); resolve(true);}.bind(this), 2000);
    }),
    new Promise(function(reject) {
      setTimeout(function() {console.log('done reject'); reject(false);}.bind(this), 4000);
    })
  ];
  
  if (some_prev && collectPending(pending).then(val => {return true;}).catch(err => {return false;})) {
    return true;
  } else {
    return false;
  }
}

function collectPending(pending) {
  var p = Promise.all(pending)
    .then(values => {
      return true;
    })
    .catch(error => {
      return false;
    });
    
  return p;
}

The valid method should return true as the form will otherwise be submitted while it contains errors.

I have also tried wrapping the Promise.all in a async function but I found that this only pushes the problem further on and in the end you always end up in a similar situation.

In essence, is there a wait to halt the execution until all promises are resolved?

Edit 27-01-2021 15:38:
As I am extending a framework, I am only allowed to overwrite the valid method. The rest of this framework expects the valid method to be sync. So I am really looking for a way to convert async back to sync instead of making all the code async. The collectPending method I wrote myself, so this one can be changes, just not the valid method.

20 thoughts on “How to halt execution until Promise is resolved”

Leave a Comment