如何“等待” setTimeout在函数内部完成然后执行函数的返回

时间:2020-05-19 09:09:41

标签: reactjs asynchronous dom load

在函数中,const htmlCollection = document.getElemenetsByClassName('elemenet-class')用于从DOM中获取所需的元素,而某些元素的属性用于函数(return htmlCollection[0].clientWidth)的返回值中。

问题在于函数的返回在加载所有DOM节点之前执行,因此当我访问htmlCollection[0]以获取所需的element时,它将获得undefined。我试过的是将代码包装在setTimeout内,偏移量为500ms,可以访问htmlCollection[0]元素,但是现在的问题是函数的返回是主线程的一部分,并且在整个setTimeout之前执行这是异步操作,因此应该作为函数“返回值”的htmlCollection[0].clientWidth仅在setTimeout内部存在。

如何“等待”加载DOM(或“等待” setTimeout执行并检索contentWrapperWidth),然后执行函数的返回?

代码:

// first try (fails because on function return, 'content-wrapper' is not loaded in DOM)
renderPreview = () => {
let htmlString = getHTML();
const contentWrapper = document.getElementsByClassName('content-wrapper');
const contentWrapperWidth = contentWrapper[0].clientWidth;

htmlString = htmlString.replace('width_placeholder', contentWrapperWidth);

return htmlString;
}


// second try (fails because function's return executes before setTimeout of course - i.e. contentWrapperWidth lives only inside setTimeout and function returns htmlString with placeholder, before replacing)
renderPreview = () => {
let htmlString = getHTML();

setTimeout(() => {
const contentWrapper = document.getElementsByClassName('content-wrapper');
const contentWrapperWidth = contentWrapper[0].clientWidth;

htmlString = htmlString.replace('width_placeholder', contentWrapperWidth);
} , 500);

return htmlString;
}

1 个答案:

答案 0 :(得分:1)

您可以使用$brickName($object)

应该在dom加载后加载功能。