How to correctly execute a loop synchronously with javascript?

Hello,

I’m trying to run this while loop in a syncronous way, i need this function to control a process checking his status querying the endpoint every x seconds after launching the process from a button on the UI.

It seems to be not running it correctly or else I’m not controlling it properly with the right code because it is not logging anything in the console. I am not experienced in javascript, could someone tell me what would be the best way to do it?

Thanks,
Ivan

current code:

export default {

	executeRoutine2: () => {
		
		function loopScanStatus() {
			
			function task() {
				setTimeout(function() {
					DP_REQUEST_SCAN_STATUS.run();
				}, 5000);
			}
			
			while (true) {
				task();
				console.log(DP_REQUEST_SCAN_STATUS.data);
				if (DP_REQUEST_SCAN_STATUS.data === "FINISHED") {
					console.log("ENDED")
				}
			}
		}
		
		DP_REQUEST_DATASTORE_SCAN.run()
			.then(() => loopScanStatus());
  }
}

@cripsisxyz I wasn’t able to view logs on the Appsmith console. I’ll create a GitHub issue for this. However, I was able to view logs on the browser console. Could you confirm if you’re able to view the same?

@bharath in my case the behavior seems to work different, its always logging undefined but the output must be always a string:

it seems is not respecting the setTimeout delay beacause the loop its executing very fast (look the iterations counter)

thank you for helping!

I think this is logging undefined in your case because of the nature of the DP_REQUEST_SCAN_STATUS query. Can you try the following:

  1. Mark your loopScanStatus as an async function like so: async function loopScanStatus() {...}
  2. Then get the result of the query separately like so:
    const data = await DB_REQUEST_SCAN_STATUS.run()
  3. Use data in your if statement.

Try this and see if it works for you

1 Like

Okay now it works!
current code:

export default {

	executeRoutine2: () => {
		
		async function loopScanStatus() {
			while (true) {
				const data = await DP_REQUEST_SCAN_STATUS.run();
				console.log(data);
				if (data === "FINISHED") {
					console.log("ENDED")
					break;
				}
			}
		}
		
		DP_REQUEST_DATASTORE_SCAN.run()
			.then(() => loopScanStatus());
  }
}

I have not been able to make the loop have a delay, but since it is waiting each time for the response from the API, it no longer executes as frequently

Thank a lot @Olawale

1 Like

Really happy to help! @cripsisxyz