Monitor the item for fluctuations in its worth

Is there a way to watch an object and wait for all of its values to become truthy?

const myObject = {
    key1: null,
    key2: null,
    key3: null,
}

// Perform asynchronous operations that update myObject

const checkValues = async () => {
    await Object.values(myObject).every(value => !!value)
    // Continue with the code
}

Answer №1

One way to achieve this is by utilizing a Proxy object.

const myObj = new Proxy({
    prop1: null,
    prop2: null,
    prop3: null,
}, {
  set(obj, prop, val){
    obj[prop] = val;
    if(val && Object.values(obj).every(x => x)) console.log('All values are truthy:', obj);
    return val;
  }
});
myObj.prop1 = true;
setTimeout(()=>{
  myObj.prop2 = true;
  myObj.prop3 = true;
}, 1000);

Another approach is to combine setTimeout with a Promise and await it within an async function.

const myObj = {
  prop1: null,
  prop2: null,
  prop3: null,
}

function checkTruthy(obj) {
  return new Promise(function f(resolve, reject) {
    if (Object.values(obj).every(v => v)) resolve();
    else setTimeout(f.bind(null, resolve, reject), 500);
  });
}
const checkValues = async() => {
  await checkTruthy(myObj);
  console.log(myObj);
}
checkValues();
myObj.prop1 = true;
setTimeout(() => {
  myObj.prop2 = true;
  myObj.prop3 = true;
}, 1000);

Answer №2

To achieve this, you can implement getters, setters, and a resolve function within your object.

let object = {
  get property1() { return this._property1 },
  get property2() { return this._property2 },
  get property3() { return this._property3 },
  set property1(value){ this._property1 = value; checkAllTruthy() },
  set property2(value){ this._property2 = value; checkAllTruthy() },
  set property3(value){ this._property3 = value; checkAllTruthy() }
};

const checkAllTruthy = () => {
  if (object.property1 && object.property2 && object.property3) console.log('Execute when all properties are truthy') 
}

object.property1 = "Alice"
object.property2 = "Bob"
console.log(object.property1)
setTimeout(() => object.property3 = "Charlie", 1000)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to include a base url for imports in React JS?

Conventional method for adding imports: import Sample from ‘../../../components/signup’ I want to simplify imports by removing the front dots and slashes: import Component from ‘components/signup’ Is there a way to set a base URL for imports to ...

Sending dynamic information to bootstrap's modal using props in VueJS

I'm currently working on a personal project and encountering an issue with the bootstrap modal. My project involves a list of projects, each one contained within a card element. The problem arises when I attempt to display details for each project by ...

Find all elements with the same class and identify the first element among them using jQuery

In my dynamic data structure, I need to filter out all elements with the class name "My_data" and select the first one. In the code below, I am looking to retrieve the first element with the class "My_data". <div class="all_data"> <div class="lis ...

The useEffect hook in my React app causes the homepage to refresh

Currently, I am facing a challenge in retrieving user information from the Redux state to display on the homepage after a user signs in. The issue arises when the component refreshes and all the data stored in Redux gets lost due to the useEffect hook im ...

When there is an absence of data, the jQuery datatable mysteriously van

I have encountered an issue in my Django app where a datatable used in the template disappears if there is missing data in any column or row. The problem occurs when trying to download the data in CSV, Excel, PDF, or copy format. Here is the HTML code snip ...

What could be the reason behind the malfunctioning of my three.js lighting system?

I am struggling to identify the issue with this code snippet (http://jsfiddle.net/resistdesign/s6npL/). Despite referencing the documentation and some examples, the lights don't seem to be functioning as expected. var camera, scene, renderer, geometr ...

The PureComponent FlatList does not refresh properly even after including extraData={this.state} as a prop

After conducting some research, I discovered that using a PureComponent instead of a regular Component can enhance the performance of my FlatList. By doing so, only the row that was changed will be re-rendered rather than the entire list. However, I encoun ...

Does it make sense to prioritize robust $routeProviders and keep controllers slim?

Traditionally in MVC architecture, models are designed to be robust and controllers are kept minimal for easier testing. However, Angular lacks a clear model structure, making it challenging to organize code for reuse. Although Angular does offer services ...

Retrieve a particular cookie from the request headers in Express framework

Today, I encountered a problem with express. Let's say we set multiple cookies, but when I check request.headers, only one cookie is returned: cookie: 'userSession=123' For instance, not only is it unreliable to use request.headers.cookie ...

delivering the optimized main RequireJS file as a static asset through NGINX servers

Is it true that serving static assets from NGINX or another server is better than using your Node.js application server? In my case, I have a single-page application where in production mode, only one optimized .js file is served from the index page, and ...

Tips for isolating all the Javascript loaded via ajax or jquery.load within a specific child scope instead of a global scope

I am currently working on a solution to embed a third-party page into my site using ajax/jquery.load() to avoid using iframes (CORS requirements are already handled by the third party). My dilemma lies in the fact that the main host site loads jquery 1.x ...

The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below ...

What is the best way to center align an element while having another element situated directly below it?

I want to create a grid of "clock" elements, with five clocks in each row. Below each clock, I'd like to display the DAY and DATE centered with the clock (day on top line, date below). Since I'm new to html/css, I appreciate your patience. Here&a ...

Transition smoothly between sections using fullPage.js with clipping path effects

I am looking to create a unique clipping animation utilizing SVG clipping path. The animation should hide the first section while revealing the second section in a smooth transition using fullPage.js. This idea is somewhat similar to the question discusse ...

Enhancing Bootstrap with VueJS for better component ordering

I've been struggling with Vue components in Bootstrap lately. I am attempting to create collapsible Bootstrap content in Vue, and here is the current code: HTML <div class="col-sm main-content" id="main-content"> <p&g ...

Having trouble displaying specific images on React Native, how can I resolve this issue?

I am currently developing a weather application that retrieves weather information and displays it using ForecastItem components. However, I have noticed that some of the components do not display the weather image randomly. On the Home screen, I use the ...

Encountering a Laravel Nova issue where attempting to override a Vue component leads to a Vue warning: Error

Recently, I decided to incorporate a user guide into my nova using the following Vue Shepherd library. To make this work, I made some adjustments in the files within the nova directory. One of these changes involved renaming the file "webpack.mix.js.dist" ...

Encountering problem with rendering the header in the footer within a customized package built on react

I am currently working on creating a node package that consists of simple HTML elements. The package is named fmg_test_header. These are the files included in the package: header.jsx index.js package.json header.js function Header() { return "< ...

Code snippet for adding a div element with an embedded image using JavaScript

I am attempting to create a function that generates three div elements, each containing an image, and then appends them to the body using a for loop. As a beginner in JavaScript, I am struggling with this task. Can anyone please provide guidance on what ...

Automatically submitting Ajax form upon loading the page

I am attempting to use ajax to automatically submit a form to a database upon page load. The form and php code work perfectly when manually submitted, but for some reason, the ajax function does not trigger. Despite checking the console for errors and con ...