Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

javascript - 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;
}
question from:https://stackoverflow.com/questions/65920970/how-to-halt-execution-until-promise-is-resolved

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Does this work as per your expectation, it is executing in the order one may want to have.

valid().then(res => console.log(res));

async 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);
    })
  ];
  // wait for collectPending to resolve 
  if (some_prev && await collectPending(pending)) {
    return true;
  } else {
    return false;
  }
}

async function collectPending(pending) {
  let result = await Promise.all(pending);
  return result.reduce((res, current) => res && current); //combines result of all the promises and return the boolean 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...