For of loop, wait until value is defined

Viewed 607

In a for of loop, I want to get a value defined (not empty) before I continue to the next iteration.

Currently, I do a setTimeout() and "hope" that the value is available after 3 seconds. Poor practice.

Is there a way to pause the loop iteration until the value is available, and then continue the loop?

// get a tags in array
const $j_object = $(".name");
        
for (const element of $j_object) {

    // timeout
    await new Promise(resolve => setTimeout(resolve, 3000));

    // get value
    value_name = await GM.getValue("value_name");

    // wait until value_name is defined until we continue...!
}
1 Answers

You could add a loop in which you keep reading the value, with some delay between the reading attempts, breaking the loop when you read something other than undefined.

while ((value_name = await GM.getValue('value_name')) === undefined) {
  await new Promise(resolve => setTimeout(resolve, 500))
}

A less dense way of writing that would be:

while (true) {
  value_name = await GM.getValue('value_name')
  if (value_name !== undefined) break
  await new Promise(resolve => setTimeout(resolve, 500))
}
Related