Issue
I am trying to run a while loop synchronously in my JavaScript code to control a process by checking its status and querying an API endpoint every few seconds. However, the loop is not logging anything in the console. This is the initial code that did not work:
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());
}
}
Resolution
The problem was that the while loop in the function loopScanStatus
was not running correctly and was not logging anything to the console. The goal was to control a process by checking its status every few seconds after launching it from a button on the UI.
The solution involved making the loopScanStatus
function asynchronous and getting the result of the query separately using await
. The new code of the JS Object looks like this:
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());
}
}
This fixed the issue, and the loop now waits for the API response before executing again. The function logs the response to the console and ends the loop once the response is "FINISHED".