Reputation: 68650
How could I observe an object and await all its values to be truthy.
const myObject = {
key1: null,
key2: null,
key3: null,
}
// do async ops that mutate myObject
const someFunction = async () => {
await Object.values(myObject).every(v => !!v)
// continue
}
Upvotes: 1
Views: 110
Reputation: 23654
Getters, setters and a resolve function in your object would do it
let obj = {
get key1() { return this._key1 },
get key2() { return this._key2 },
get key3() { return this._key3 },
set key1(v){ this._key1 = v; isAllTruthy() },
set key2(v){ this._key2 = v; isAllTruthy() },
set key3(v){ this._key3 = v; isAllTruthy() }
};
const isAllTruthy = () => {
if (obj.key1 && obj.key2 && obj.key3) console.log('doWhenTruthy')
}
obj.key1 = "john"
obj.key2 = "bill"
console.log(obj.key1)
setTimeout(() => obj.key3 = "sally", 1000)
Upvotes: 1
Reputation: 89214
You can use a Proxy
.
const myObject = new Proxy({
key1: null,
key2: null,
key3: null,
}, {
set(obj, prop, val){
obj[prop] = val;
if(val && Object.values(obj).every(x => x)) console.log('All truthy:', obj);
return val;
}
});
myObject.key1 = true;
setTimeout(()=>{
myObject.key2 = true;
myObject.key3 = true;
}, 1000);
You could use setTimeout
with a Promise
to await
it inside an async
function.
const myObject = {
key1: null,
key2: null,
key3: null,
}
function allTruthy(object) {
return new Promise(function f(resolve, reject) {
if (Object.values(object).every(v => v)) resolve();
else setTimeout(f.bind(null, resolve, reject), 500);
});
}
const someFunction = async() => {
await allTruthy(myObject);
console.log(myObject);
}
someFunction();
myObject.key1 = true;
setTimeout(() => {
myObject.key2 = true;
myObject.key3 = true;
}, 1000);
Upvotes: 3