【问题标题】:Get value from setTimout inside a forEach从 forEach 中的 setTimeout 获取值
【发布时间】:2021-10-17 12:41:22
【问题描述】:

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

【问题讨论】:

    标签: javascript asynchronous foreach settimeout


    【解决方案1】:

    改用两个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;
    }
    

    这将返回一个解析为点击的 div 数量的 Promise。

    【讨论】:

    • 非常有趣。但现在我遇到的问题是它只返回一个 Promise。为此,我将使用以下内容:const notificationsObserver = new MutationObserver((mutations) => { const removedNeedlessNotifications = await removeNeedlessNotifications(mutations); } 但我只得到文本。我对异步/等待很糟糕:(
    • 你需要消耗 Promise。要么使回调异步,以便您可以等待它,要么在 Promise 上调用 .then
    • 小问题await new Promise(resolve => setTimeout(resolve, 100));await new Promise((resolve) => setTimeout(resolve, 100));有区别吗?
    • 不,它们完全一样。当只有一个参数时,箭头函数参数周围的括号是可选的。
    • 当你有至少两个 Promise 可以使用时,异步函数是很好的,IMO。否则,我认为使用.then 会使语法更容易。
    猜你喜欢
    • 2018-02-17
    • 2012-08-25
    • 1970-01-01
    • 2014-09-15
    • 2015-01-27
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多