-1

This is maybe an unusual situation, but I'm writing a Chrome extension that iterates through elements on a webpage. To do this, I'm going through the children of the main div using a for-loop, like below:

function grab_data() {
    //element in the DOM which contains the transcript history
    var parent_elem = document.querySelector("#yDmH0d > c-wiz > div > div.jkOv3d > c-wiz:nth-child(4) > c-wiz > c-wiz > div > div:nth-child(1)");
    for (let i = 0; i < (parent_elem.children.length); i++) {
        if (parent_elem.children[i].hasAttribute("data-timestamp")) {
            //regular case, handle data normally
            some_code();
        }
        else {
            // this is the special case, click a button and the mutation observer will be triggered
            example_button.click();
        }

In the else block, I need to wait for data that is grabbed in the callback function of the mutation observer before continuing on to the next iteration of the loop. Is this possible? How can I go about doing this?

Emilie
  • 25
  • 1
  • 6
  • You can use `break` in `loop`, https://www.w3schools.com/js/js_break.asp – Ali Yaghoubi Oct 26 '21 at 17:45
  • 1
    I think you can do it with `promise`. Check this link out: https://stackoverflow.com/questions/21518381/proper-way-to-wait-for-one-function-to-finish-before-continuing – Mani Mirjavadi Oct 26 '21 at 17:49

1 Answers1

0

That behavior can be achieved using promises.

function asyncFunction(i){
    setTimeout(() => {
            console.log(i);
        }, 500 * i);
}

async function mainLoop() {
    for(let i = 0; i < 10; i++){
       await asyncFunction(i);
    }
}

mainLoop()

Where asyncFunction is your callback.

That way your main loop will wait until the callback is resolved. I am not sure if this is a good practice, though.