DEV Community

Discussion on: Using a Promise in a click eventListener - more than once.

Collapse
 
alittlebyte profile image
Vlad • Edited

I am, probably didn't describe it too well.
There's a model block above view that isn't included, it's responsible for API calls.

The current flow is:

  • Initial call, loading collections. (it's written the same way, but it should only execute once, so not included - works as intended)
  • Setting up an eventListener that should not activate, until an element is clicked.
  • When it's clicked, send a call with the clicked element's ID to the model. The id is that of the collection.
  • It then returns the list of photos for that collection, which is then rendered.

If I do everything synchronously, sendPhotos() model function will return an undefined error. There's only an axios call in it, and it has to wait for the ID to be defined first. Making this function async/await doesn't work, tried.

All I really wanted to know is if there's an alternative for Promises, that can be re-resolved, and searching for one hasn't given any good results. I did find a thing called Observables, but it was reserved for Angular only, and I'm making the app in vanilla JS.
Or, a way to hold await until an element is clicked and its ID is sent to it. But await only works that way with Promises, so not much to do there.

Collapse
 
copperwall profile image
Chris Opperwall

I might be wrong, but I think one way would be to pass a callback into returnCollectionsId and then call that callback from inside returnCollectionsId from the click event handler you set up. Then anytime element1 is clicked, your callback will be called, instead of just the first time.

If you wanted to use Observables I think you could use Rx.js without angular. Instead of returning a promise that sets up an on click handler and resolves when the onClick is called for the first time, you can return an Observable and subscribe to it in whatever code calls returnCollectionsId.

Here's a blog post about setting up Rx.js with click events from a few years ago codyburleson.com/respond-to-button...

Thread Thread
 
alittlebyte profile image
Vlad • Edited

Thank you, I've tried both. The way I made everything, it doesn't want to wait for anything else but a Promise, unfortunately. Still launches immediately. Or I need a couple more days for the new information to sink in, and then I'll figure out how to get it to work. Will see, thank you again!