我有下面的函数,它检查selector指定的元素是否在页面上。
此代码在元素加载之前加载页面时运行。因此,它将继续尝试查找该元素,直到达到最大timeout,然后是return false
function rafAsync() {
return new Promise(resolve => {
requestAnimationFrame(resolve);
});
}
export default async function checkElement(timeout = 20) {
let counter = 0;
while (document.querySelector(selector) === null) {
counter = counter + 1;
if (counter > timeout) return false;
await rafAsync();
}
return document.querySelector(selector);
}问题是我需要支持Safari10和其他一些不支持async/await的浏览器。
我如何才能在不需要await的情况下工作,但如果找到了元素,仍然返回它?
对checkElement函数的调用如下:
lookForElement() {
this.checkElement(selectorTimeout).then(element => {
this.element = element;
if (!this.element) {
debug("Sorry, we couldn't find your element");
return;
}
// ...continue
});}
发布于 2018-02-15 20:59:56
一种选择是通过Babel或Traceur等转译器将ES2017转换为ES2015或ES5。
如果您想手动完成此操作,就像您在the MDN page中看到的那样,async函数是promise创建和消费的语法糖。async函数返回一个promise。它从一些同步代码开始,然后返回程序流中遇到的第一个await或return的promise。
该函数非常简单,因此很容易重写:
export default function checkElement(timeout = 20) {
// Create and return our promise
return new Promise((resolve, reject) => {
// Initialize counter and do first check
let counter = 0;
check();
function check() {
// Got the element?
let element = document.querySelector(selector);
if (element != null) {
// Yes, resolve the promise
resolve(element);
} else {
// No, timeout?
counter = counter + 1; // ++counter; or counter++; would be more idiomatic
if (counter > timeout) {
// Yes
resolve(false); // rejecting here would be more idiomatic, but that's not what your `async` function did
} else {
// No, check again on next RAF
rafAsync().then(check);
}
}
});
}https://stackoverflow.com/questions/48807528
复制相似问题