首页 > 解决方案 > 从 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();
}

标签: javascriptasynchronousforeachsettimeout

解决方案


改用两个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 的数量。


推荐阅读