javascript - 从 forEach 中的 setTimout 获取值
问题描述
我现在在这里花了几个小时阅读这个问题的解决方案,如下所示: Get return value from setTimeout
但我找不到任何解决我的问题的方法来获取 removeCount 值。我也尝试添加一个 Promise,但我不知道如何使用增量来做到这一点。
async function removeNeedlessNotifications(mutations) {
const getResult = async () => {
let removeCount = 0;
mutations.forEach((v) =>
v.addedNodes.forEach((v, i) =>
setTimeout(() => {
if (notificationFilter(v)) {
v.querySelector("div.activity-remove.js-remove").click();
removeCount++;
}
}, i * 100)
)
);
return removeCount;
};
return await getResult();
}
解决方案
改用两个for
循环,这样你就可以await
在里面了,它变得微不足道:
async function removeNeedlessNotifications(mutations) {
let removeCount = 0;
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
await new Promise(r => setTimeout(r, 100));
if (notificationFilter(node)) {
node.querySelector("div.activity-remove.js-remove").click();
removeCount++;
}
}
}
return removeCount;
}
这将返回一个 Promise,它解析为单击的 div 的数量。
推荐阅读
- java - 当我尝试保存测试计划时,为什么会收到 NoClassDefFound 错误?
- javascript - 如何从 django 中的日期选择器中获取日期
- python - 发现是什么阻碍了事件循环
- php - 哪些 PHP 函数是不可调用的?
- windows - mvn -v 适用于 Git Bash 但不适用于 Windows cmd
- javascript - 是否可以使用 JavaScript 从 Excel 电子表格中获取特定的单元格值?
- python - 使用 cx_Oracle.lob.read() 从 Oracle 数据库读取 BLOB 不起作用
- r - 使用 dplyr 而不是 plyr 重写函数
- python - 使用 TensorFlow 在图像上绘制点
- c++ - 如何解析一棵大树?