Do you need help creating a promise that resolves when a list of booleans are all true?
I have developed a function that accomplishes this task. It accepts an object of boolean values as input and returns a promise that resolves when all the booleans become true.
Below is the implementation of the function:
function createPromiseForTrueBooleans(boolList) {
return new Promise(function (resolve, reject) {
var allTrue = true;
Object.values(boolList).forEach(function (value) {
if (!value) allTrue = false;
});
if (allTrue) {
resolve();
} else {
var _actualData = Object.assign({}, boolList);
Object.entries(boolList).forEach(function ([name, value]) {
Object.defineProperty(boolList, name, {
configurable: true,
set: function (newVal) {
var areAllTrue = true;
_actualData[name] = newVal;
Object.values(_actualData).forEach(function (val) {
if (!val) areAllTrue = false;
});
if (areAllTrue) {
Object.entries(_actualData).forEach(function ([key, val]) {
Object.defineProperty(boolList, key, {
configurable: true,
value: val,
});
});
resolve();
}
},
get: function () {
return _actualData[name];
}
});
});
}
});
}
To use this function, create an object with boolean values and pass it as an argument to the function. The promise returned will resolve when all the boolean values in the object become true.
var myBooleanList = {"ready": false, "completed": false};
createPromiseForTrueBooleans(myBooleanList).then(function () {
console.log("All boolean values are now true!");
}, function (error) {
console.error(error);
});
myBooleanList.ready = true;
myBooleanList.completed = true;
Feel free to check out the working example provided above!
The function utilizes :set and :get accessors for each key in the boolean object. The :set function triggers whenever a value is set and checks if all boolean values are true before resolving the promise.
If you'd like to learn more about :get and :set, check out this helpful article: