【问题标题】:Return true from Settimeout从 Settimeout 返回 true
【发布时间】:2021-06-23 10:49:29
【问题描述】:

我知道could 可以通过多种方式实现。而且我也明白 settimeout 是异步的,如果没有承诺,就不能轻易返回“true”。

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

从这个 sn-p 代码中,我可以返回 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;
});

【问题讨论】:

    标签: javascript asynchronous dom callback settimeout


    【解决方案1】:

    最好不要混合使用承诺和回调。准备好后只需调用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()

    【讨论】:

    • 谢谢@georg!我不认为这会返回“true”。我可以看到返回了一个承诺: Promise {: undefined} proto: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: undefined
    • @ReenaVerma waitForElement() 承诺与元素一起实现。 main() 承诺与 undefined 实现。在任何时候你都不需要值true
    • 你不能从异步函数返回任何东西,见stackoverflow.com/questions/14220321/…
    • 好的,谢谢。我正在使用的应用程序专门寻找“返回真实/或某事”而不是承诺。我想知道是否有其他方法可以实现这一目标?
    • 如果您有一个严格同步的流程,那么您无法将异步操作集成到其中。 Javascript 不能只是停止运行并等待某事。
    猜你喜欢
    • 2018-07-31
    • 1970-01-01
    • 2014-09-15
    • 2022-01-04
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    相关资源
    最近更新 更多