if I call this function, it doesn't seem to work. what it's doing is just waiting for global variable "window.AppApi" to be initialized before doing things
i feel like maybe it's because i'm calling the function again in the time out? is there something I'm missing to make this work? if it's not possible what would be a good alternative..
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 );
}
});
};
Technically you can do it even without dirty timeouts with old good Object.defineProperty setter:
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)