如何延迟JS函数返回值直至指定Cookie或对象存在
解决方案
核心思路
原函数是同步返回布尔值,但要等待OptanonConsent Cookie或OnetrustActiveGroups对象存在,必须将其改为异步模式(返回Promise或使用回调)。核心逻辑是先等待目标条件满足,再执行原有的权限检查逻辑。
方案1:Promise + 轮询(通用推荐)
这种方式兼容性好,适用于大多数场景:
// 封装等待条件满足的函数 function waitForConsentReady() { return new Promise((resolve) => { // 先检查是否已满足条件 if (checkConsentExists()) { resolve(); return; } // 轮询检查,间隔可根据需求调整(示例为200ms) const interval = setInterval(() => { if (checkConsentExists()) { clearInterval(interval); resolve(); } }, 200); }); } // 你无需实现此函数,仅作为占位表示检查逻辑 function checkConsentExists() { return document.cookie.includes('OptanonConsent') || typeof OnetrustActiveGroups !== 'undefined'; } // 修改原函数为异步版本,返回Promise async function getConsentStatus(cat, catSub, catSubCheck) { // 等待条件满足后再执行原逻辑 await waitForConsentReady(); // 替换为你实际的case判断逻辑 switch(cat) { case 'analytics': return catSubCheck === 'allowed'; case 'marketing': return catSub === 'enabled'; default: return false; } } // 调用方式(需通过then或await获取结果) getConsentStatus(event.cat, event.catSub, event.catSubCheck) .then(consentStatus => { // 此处处理返回的true/false console.log('权限状态:', consentStatus); });
方案2:回调函数(兼容旧环境)
如果环境不支持async/await,可以用回调模式实现:
function waitForConsentReady(callback) { if (checkConsentExists()) { callback(); return; } const interval = setInterval(() => { if (checkConsentExists()) { clearInterval(interval); callback(); } }, 200); } function getConsentStatus(cat, catSub, catSubCheck, callback) { waitForConsentReady(() => { // 替换为你实际的case判断逻辑 let consentStatus = false; switch(cat) { case 'analytics': consentStatus = catSubCheck === 'allowed'; break; } callback(consentStatus); }); } // 调用方式 getConsentStatus(event.cat, event.catSub, event.catSubCheck, (consentStatus) => { console.log('权限状态:', consentStatus); });
额外优化:Cookie变化监听(可选)
如果想减少轮询开销,可以结合Cookie变化事件(作为轮询的补充,兼容部分场景):
function waitForConsentReady() { return new Promise((resolve) => { if (checkConsentExists()) { resolve(); return; } // 监听Cookie变化事件 window.addEventListener('cookiechange', (e) => { if (e.changed.some(c => c.name === 'OptanonConsent') || typeof OnetrustActiveGroups !== 'undefined') { resolve(); } }); // 保留轮询作为降级方案,避免监听失效 const interval = setInterval(() => { if (checkConsentExists()) { clearInterval(interval); resolve(); } }, 500); }); }
内容的提问来源于stack exchange,提问作者Michael Johns
相关产品推荐
相关产品推荐

