Issue with setFieldValue and next() in a loop

Hi,

I have two datasets with the same number of items and I’m using a loop to compare two date fields. If both dates are equal or less than today I want to set a field value of the first dataset to false.

It seems to be an issue with the setFieldValue or next() methods, like the loop is continuing before the save is completed or something… I tried many things but I just can’t figure it out.

Any guidance is appreciated! Here’s my code:

export function button1_click(event, $w) {
	 
	let today = new Date();
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);	
	
	const numberOfItems = $w("#dataset1").getTotalCount();
	
	var item_A = $w("#dataset1").getCurrentItem();
	var item_B = $w("#dataset2").getCurrentItem();	
	
	if((item_A.reviewDate <= today) && (item_B.reviewDate <= today))
	{		
		$w("#dataset1").setFieldValue("study", false);
		$w("#dataset1").save();				
	}
	
	for(var i = 0; i < (numberOfItems - 1); i++)
	{
		$w("#dataset1").next().then( (_item_A) => {	
  		$w("#dataset2").next().then( (_item_B) => {
  	
	if((_item_A.reviewDate <= today) && (_item_B.reviewDate <= today))
		{
		$w("#dataset1").setFieldValue("study", false);
		$w("#dataset1").save();	
		}  
    
  		} );
  	} );	
	}    
}

1 Like

Hi,

Save() returns a promise that resolves once the save process is complete.
add a .then() after the save to execute code only after the save function returns.
See the example here

Hi Idon, thanks, I understand what you’re saying, but in my code I’m already using .then after the next() methods which already saves the current item before going to the next, so the save() is really redundant.

The issue is that I need a way to get the itens with the same index (one from each dataset) at the same time. I tried that in the code above using a next() inside another next() but this results with the first dataset being at the “i+1” index while the second dataset is still at the " i " index.

How could I write these two next() methods in a way that when I call the getCurrentItem() method for both datasets I would be getting the exact same indexes of each dataset ? (ie. A1 with B1, A2 with B2, etc)

Same prroblem here…

Wagner, I’ve found a way arround this problem that worked for my specific case. I’m not sure it will work for yours, but here it is anyway:

I simply combined those two datasets in only one dataset. This way you can compare the two fields (which now belong to the same dataset) at the same time because they both are part of the same ‘‘current item’’.