首页 > 解决方案 > 从 Settimeout 返回 true

问题描述

我知道有很多方法could可以做到这一点。而且我也理解 settimeout 是异步的,并且“true”不能轻易返回,没有承诺。

但我正在努力从这个函数中返回 true,并做出承诺。

从这段代码中,我可以返回 true 的最佳方式是什么?(如果元素存在,我想返回 true)。

我需要能够专门返回true

还是有另一种方法可以实现这一目标。等待 DOM 元素存在于页面上并true在它存在时返回?

function waitForElement(className, callBack){
    return new Promise(function(resolve) {
        window.setTimeout(function(resolve){
            var element = document.querySelector(className);
            if(element) {
                callBack(className, element);
                console.log("Element exists")
            } else {
                waitForElement(className, callBack);
                console.log("Wait...")
            }
        },1000)
    });
};

waitForElement(".helping-hand-sliding-data h2",function(){
    return true;
});

标签: javascriptasynchronousdomcallbacksettimeout

解决方案


最好不要混合使用承诺和回调。只需resolve(element)在它准备好后调用await整个事情:

function waitForElement(className) {
    return new Promise(function (resolve) {
        function wait() {
            let element = document.querySelector(className);
            if (element) {
                resolve(element)
            } else {
                window.setTimeout(wait, 500)
                console.log("Wait...")
            }
        }
        wait()
    });
}

setTimeout(function() {
    let fake = document.createElement('div')
    fake.className = 'helping-hand-sliding-data'
    document.body.appendChild(fake)
}, 2000)


async function main() {
    let element = await waitForElement(".helping-hand-sliding-data");
    console.log('FOUND!', element)
}

main()


推荐阅读