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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…