Skip to content
Advertisement

Rewrite MutationObserver() with async/await

How can I write this mutation observer code, using async/await?

I want to return true after console.log("Button is appearing...");. Could someone show me the best way to write this code?

I also need to clarify, this code is watching for a button, which appears and then disappears. And the reappears again, multiple times.

So the mutationObserver, is watching for the button to appear multiple times. Not just once.

JavaScript

Advertisement

Answer

Preface: I would strongly recommend not relying on a mutation observer to watch for a button’s class attribute to change. It’s very much a last resort thing to do. Look for anything else you can hook into that happens which is what makes the button appear/disappear and hook into that instead.

But getting to your question:

Since you want repeated notifications, promises (and thus async/await) is not the right model for this. A promise is only settled once.

There’s no JavaScript built-in for it, but what you want is often called an observable and it has (typically) subscribe and unsubscribe methods. Here’s a really basic, naive implementation of an observable (using modern JavaScript; run it through Babel or similar if you need to support older environments), but you may want to go looking for a library (such as Rx.js — not an endorsement, I haven’t used it, just an example I happen to know about) with something more feature-rich and, you know, tested:

JavaScript

Then you might create an observable for this mutation:

JavaScript

Once you’d set that observable up, you could subscribe to it:

JavaScript

Live Exmaple:

JavaScript
JavaScript
JavaScript

All of that is very off-the-cuff. Again, you might look for robust libraries, etc.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement