我正在try 在每次递归函数调用之前设置一个延迟.目前,它的回报率为undefined.问题可能是递归调用的作用域(在setTimeout内,然后). 我试了一下,是这样的:

    function delay(ms) {
        return new Promise(resolve => {
            setTimeout(resolve, ms)
        });
    } 

    const checkIfListElementIsRendered = (className) => {
        delay(10).then(function (res) {
            if (document.getElementsByClassName(className)[0]) {
                return true;
            }
            return checkIfListElementIsRendered(className);
        })
    }

还有这个:

    const checkIfListElementIsRendered = (className) => {
        if (document.getElementsByClassName(className)[0]) {
            return true;
        }
            
        setTimeout(() => {
            return checkIfListElementIsRendered(className);
        }, 10);   
    }

如有任何帮助,我们不胜感激!

推荐答案

您需要将checkIfListElementIsRendered转换为async/await的语法,而awaitdelaycheckIfListElementIsRendered方法也返回true将其转换为promise以始终返回promise.

当你在外部调用checkIfListElementIsRendered方法时,需要用awaitthen回调来解析.

function delay(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms)
    });
} 

const checkIfListElementIsRendered = async (className) => {
   await delay(10)
   if (document.getElementsByClassName(className)[0]) {
      return Promise.resolve(true);
   }
   return await checkIfListElementIsRendered(className);
}

Javascript相关问答推荐

分层树视图

我的角模板订阅后不刷新'

如何迭代叔父元素的子HTML元素

正则表达式,允许我匹配除已定义的子字符串之外的所有内容

查询参数未在我的Next.js应用路由接口中定义

让chart.js饼图中的一个切片变厚?

在画布中调整边上反弹框的大小失败

打字脚本中方括号符号属性访问和拾取实用程序的区别

在D3条形图中对具有相同X值的多条记录进行分组

如何更改Html元素S的 colored颜色 ,然后将其褪色为原始 colored颜色

无法使用npm install安装react-dom、react和next

FindByIdAndUpdate在嵌套对象中创建_id

在使用JavaScript以HTML格式显示Google Drive中的图像时遇到问题

在HTML中使用meta标记来指定定制元数据以用于使用JavaScript进行检索是不是一个坏主意?

JavaScript -如何跳过某个字符(S)来打乱字符串中的字符

打字脚本中的函数包装键入

JQuery-无法 Select 使用elementor添加的元素的值

Iterator.Next不是进行socket.end()调用后的函数

为什么我的reducer函数被多次调用?

Jsyaml SafeDump打字支持