如果我调用此函数,它似乎不起作用。它所做的只是在执行操作之前等待全局变量“ window.AppApi”被初始化
我觉得可能是因为我在超时时间内再次调用了该函数?有什么我需要使这项工作吗?如果不可能的话,那将是一个很好的选择。
initializeApp()
.then(( result ) => {
console.log( 'it worked!' ); // does not go here
});
export const initializeApp = () => {
return new Promise(( resolve, reject ) => {
// wait for App API to be initialized
if ( window.AppApi ) {
console.log( 'App initialized.' );
resolve( true );
}
else {
console.log( 'waiting for App to initialize...' );
setTimeout( () => initializeApp(), 250 );
}
});
};
最佳答案
从技术上讲,即使使用旧的良好的Object.defineProperty设置器,也可以避免超时超时:
const initializeApp = () => {
return new Promise((resolve, reject) => {
if (window.AppApi) {
resolve(true);
return;
}
Object.defineProperty(window, 'AppApi', {
set (value) {
console.log('App initialized.');
resolve(true);
return value
}
})
});
};
initializeApp()
.then((result) => {
console.log('it worked!'); // does not go here
});
setTimeout(() => {
window.AppApi = { test: 123 }
}, 2000)