I am very new to promises and would 1) like to have this do what it needs to do, and 2) get feedback on the 'more correct' way to write it or any efficiencies that can be added.
The goal: Check for the existence of an ID. If it exists, assign the node to a variable and then have a MutationObserver observe it for changes. If the ID does not exist, do not attempt to instantiate the observer.
The issue: If the ID exists on the page, it will always take a bit to load. And I'm sure I'm not handling the 'if it doesn't exist' portion correctly. And currently the variable is coming back false even when the ID eventually exists on the page.
The code:
document.addEventListener( 'DOMContentLoaded', () => {
let control = false;
function getControls() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([
document.getElementById('controls')
]);
}, 2000);
});
}
getControls().then((node) => {
control = node;
});
console.log(layout_control); // currently false; Maybe there's a better way than setting an arbitrary timeout.
if (!control) {
return;
} // Maybe this should be to do with 'reject.'
new MutationObserver( function() {
// Do some things when the controls change.
} ).observe( control, {
subtree: true,
childList: true
}
);
} );
Your code won't work, because the if statement will execute before the promise fulfills
I would just use this:
document.addEventListener("DOMContentLoaded", () => {
function getControls() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([document.getElementById("controls")]);
}, 2000);
});
}
getControls().then((node) => {
new MutationObserver(function () {}).observe(node, {
subtree: true,
childList: true,
});
});
});
or
document.addEventListener("DOMContentLoaded", async () => {
function getControls() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([document.getElementById("controls")]);
}, 2000);
});
}
const node = await getControls();
new MutationObserver(function () {}).observe(node, {
subtree: true,
childList: true,
});
});