uzairfarooq / arrive

Watch for DOM elements creation and removal
MIT License
874 stars 99 forks source link

Promise and Async/Await Support #80

Open dw1284 opened 3 years ago

dw1284 commented 3 years ago

Not sure if this is possible, or if it is already implemented. It would be nice to use Async/Await with this library.

Example

const element = await document.arrive('#elementId', {onceOnly: true, existing: true});
// do stuff with element

Instead of this:

document.arrive('#elementId', {onceOnly: true, existing: true}, function() {
  const element = this;
  // do stuff with element
});
dw1284 commented 3 years ago

For anybody who wants to manually promisify the library, just insert this snippet somewhere in your code after your arrive.js import:

const objects = [HTMLElement, NodeList, HTMLCollection, HTMLDocument, Window];

const promisifiedArrive = function(a, b) {return new Promise((resolve) => {this.arriveWithCallback(a, b, resolve);})};
const promisifiedLeave = function(a, b) {return new Promise((resolve) => {this.leaveWithCallback(a, b, resolve);})};

objects.forEach(object => {
  object.prototype.arriveWithCallback = object.prototype.arrive;
  object.prototype.leaveWithCallback = object.prototype.leave;
  object.prototype.arrive = promisifiedArrive;
  object.prototype.leave = promisifiedLeave;
});

The following will now work:

const element = await document.arrive('#elementId', {onceOnly: true, existing: true});
// do stuff with element
dw1284 commented 3 years ago

I went ahead and added async/await support myself and created a PR: https://github.com/uzairfarooq/arrive/pull/81

tcaruth commented 3 years ago

For any future issue readers: the dev branch on this repo adds this functionality.

If you don't need to use npm, arrive.js(dev) contains these changes

dmatora commented 2 years ago

Thank you guys!