javascript - 从 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;
});
解决方案
最好不要混合使用承诺和回调。只需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()
推荐阅读
- ios - 快速使用 Pan 音频
- python - 如何在TensorFlow中沿维度选择张量的元素(不是切片)
- python-3.x - 是否可以从相同的代码同时执行 2 个或更多的海龟窗口(Tk)?
- google-cloud-platform - 针对 Campaign Manager 数据的 BigQuery Data Transfer Service 基准
- python - 即使代码与手册相同,Mygene 仍显示 AttributeError
- windows - 安装后无法在cmd上运行composer
- android - 如何在android中保持地图方向固定在北方
- python-3.x - 计算列表中坐标之间的距离
- spring-boot - 部署 Spring Boot 项目时 PCF 内部如何工作
- html - 如何将2个div放在同一个位置?