
本文介绍如何使用 JavaScript Promise 实现对对象属性(如 isLoaded)的异步监听,当其值变为 true 时自动触发后续逻辑,适用于项目加载、资源就绪等典型场景。
本文介绍如何使用 javascript promise 实现对对象属性(如 `isloaded`)的异步监听,当其值变为 `true` 时自动触发后续逻辑,适用于项目加载、资源就绪等典型场景。
在前端开发中,常需等待某个状态标志(例如 document.isLoaded)变为 true 后再执行依赖该状态的操作。由于该属性通常由异步加载逻辑(如 API 请求、文件解析)设置,直接轮询 + Promise 封装是一种轻量、兼容性好且无需修改原对象的通用方案。
以下是一个健壮的 waitForLoaded 工具函数实现:
function waitForLoaded(documentStore, options = {}) {
const { timeout = 10000, interval = 100, errorMessage = 'Timeout waiting for isLoaded' } = options;
return new Promise((resolve, reject) => {
const startTime = Date.now();
const check = () => {
// 立即检查,避免不必要的延迟
if (documentStore?.isLoaded === true) {
resolve();
return;
}
// 超时保护
if (Date.now() - startTime > timeout) {
reject(new Error(errorMessage));
return;
}
// 继续轮询
setTimeout(check, interval);
};
check();
});
}
使用示例:
// 假设 yourDocumentStoreObject 是已初始化的对象
waitForLoaded(yourDocumentStoreObject, {
timeout: 5000, // 最长等待 5 秒
interval: 50 // 每 50ms 检查一次
})
.then(() => {
console.log('✅ Document is fully loaded — now triggering X...');
// ✅ 此处执行你的业务逻辑:渲染 UI、启用按钮、发起关联请求等
})
.catch(err => {
console.error('❌ Failed to wait for load:', err.message);
// 可选择降级处理或提示用户重试
});
⚠️ 注意事项与最佳实践:
- 避免高频轮询:将 interval 设置为 50–100ms 平衡响应性与性能;切勿使用 0(会导致微任务风暴)。
- 务必添加超时机制:防止因状态永远不满足导致 Promise 永远不兑现,引发内存泄漏或界面假死。
- 增强健壮性:使用可选链 documentStore?.isLoaded 防止对象为空时报错。
- 进阶替代方案:若可修改 documentStore,推荐改用 EventTarget(派发 'loaded' 事件)或 Observable(如 RxJS),更符合响应式编程范式,但需侵入式改造。
该方法无需第三方库、兼容所有现代浏览器及 Node.js 环境,是解决“等待任意布尔状态就绪”问题的经典实用模式。










