从 forEach 中的 setTimeout 获取值

Get value from setTimout inside a forEach

我现在已经花了几个小时阅读这个问题的解决方案,如下所示: 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;
}

这将 return 解析为点击的 div 数量的 Promise。