gpt4 book ai didi

async-await - JavaScript : how can I use async/await to "await" something that happens in MutationObserver?

转载 作者:行者123 更新时间:2023-12-01 01:47:05 27 4
gpt4 key购买 nike

我有一个 forEach循环处理数组中的数据。在该循环中间的某个地方,我必须等待 DOM 元素的更改,获取该更改,处理它,然后才能继续处理数组。

我希望在控制台中看到这个:

Preparing "aaa"
Waiting for result on "aaa"
Processing result on "aaa": <random number>
Got result for "aaa": <random number>something`

对于 stuffToProcess 中的每个元素也是一样的下面的代码片段中的数组。这是代码的简化示例。

我意识到类似的问题之前已经被问过无数次并得到了回答,但是在阅读了其中的许多问题并尝试了许多不同的事情数小时后,我仍然无法弄清楚这一点。

function dummy() {
$('#trackMe').text(Math.random());
}

async function doWork(stuffToProcess) {
let target = $('#trackMe')[0];
let config = { attributes: true, childList: true, characterData: true, values: true };

let observer = new MutationObserver(function(mutations,item) {
console.log('Processing result on "%s": %s', item, target.innerText);
item = item + 'something';
return new Promise(resolve => {
resolve(item);
});
});

observer.observe(target, config);

stuffToProcess.forEach(async function(item) {
console.log('Preparing "%s"', item);
console.log('Waiting for result on "%s"', item);
let change = await observer(item);
//^^^ this needs to "await" for data from observer before the loop continues
console.log('Got result for "%s": %s', item, change);
});

//observer.disconnect();

}

doWork(['aaa', 'bbb', 'ccc']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="trackMe">No changes yet</p>
<button onclick="dummy()">Click me to change</button>

最佳答案

好吧,我设法以某种方式解决了它。不过,可能不是最干净的解决方案,所以如果有人建议对此进行任何改进,我会很乐意编辑解决方案/投票赞成您的答案。

function dummy() {
$('#trackMe').text(Math.random());
}

async function doWork(stuffToProcess) {
let target = $('#trackMe')[0];
let config = {
attributes: true,
childList: true,
characterData: true,
values: true
};

let observer;

function isItDone(item) {
return new Promise(resolve => {

observer = new MutationObserver(function(mutations) {
console.log('Processing result on "%s": %s', item, target.innerText);
result = target.innerText + 'something';
resolve(result);
});

observer.observe(target, config);
});
}


for (index in stuffToProcess) {
console.log('Preparing "%s"', stuffToProcess[index]);
console.log('Waiting for result on "%s"', stuffToProcess[index]);

let change = await isItDone(stuffToProcess[index]);
observer.disconnect();

console.log('Got result for "%s": %s', stuffToProcess[index], change);
}
}

doWork(['aaa', 'bbb', 'ccc']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="trackMe">No changes yet</p>
<button onclick="dummy()">Click me to change</button>

关于async-await - JavaScript : how can I use async/await to "await" something that happens in MutationObserver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757042/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com