简体   繁体   English

在等待突变观察者的响应时暂停 javascript for 循环?

[英]Pause javascript for-loop while waiting for response from mutation observer?

This is maybe an unusual situation, but I'm writing a Chrome extension that iterates through elements on a webpage.这可能是一种不寻常的情况,但我正在编写一个 Chrome 扩展程序,它遍历网页上的元素。 To do this, I'm going through the children of the main div using a for-loop, like below:为此,我将使用 for 循环遍历主 div 的子级,如下所示:

 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.在 else 块中,在继续循环的下一次迭代之前,我需要等待在变异观察者的回调函数中获取的数据。 Is this possible?这可能吗? How can I go about doing this?我该怎么做呢?

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.其中 asyncFunction 是您的回调。

That way your main loop will wait until the callback is resolved.这样你的主循环将等到回调解决。 I am not sure if this is a good practice, though.不过,我不确定这是否是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM