2

I have custom event.

$('body').on('searchPlaceOnWebMap', (event, payload) =>
  this.webMap.getPlaces(payload).then(data => data)
);

I get google places in my getplaces promise function, this function return data for me. If I write .then(data => { console.log(data) }) I see result.

Then I try get data after trigger

const result = $('body').trigger('searchPlaceOnWebMap', searchValue)

But I can't do it.

How I can get return value after trigger?

2 Answers2

4

You can't directly return a value from an event handler. You would need to pass your Promise using the event object. jQuery does this automatically by assigning the value to the result property of the event object:

event.result

Description: The last value returned by an event handler that was triggered by this event, unless the value was undefined.

$('body').on('searchPlaceOnWebMap', (event, payload) => this.webMap.getPlaces(payload));

That is equal to:

$('body').on('searchPlaceOnWebMap', (event, payload) => {
  event.result = this.webMap.getPlaces(payload)
});

And to be able to access the returned Promise after your trigger, you need to create a custom event object that you pass to the trigger function:

var e = jQuery.Event("searchPlaceOnWebMap");
$('body').trigger(e, obj)

//e.result now holds the promise
e.result.then(value => {
  // do something with value
})
t.niese
  • 39,256
  • 9
  • 74
  • 101
0

The best answer to your question as asked is that you shouldn't try to access the results after the event handler gets triggered. Instead, you want to put the code that uses the promise result inside the .then() callback.

Think of it like this: Javascript programming is very event-driven. What this means is that you are writing code all the time that says "when foo happens, run function bar". And this type of code is often nested, and that's fine, for a sequence of events.

In your case, you want to write code that expresses the following:

Whenever a searchPlaceOnWebMap event gets triggered, make a call to get matching places based on the payload of the event. When that call returns, then do something with the results.

The way to do something with the results in this case, because .getPlaces() returns a promise, is to use .then(results => doSomething(results)) or async/await syntax if that is available for you.

But the important thing is to realize that because you don't know when the promise is going to resolve, you can't immediately access it's results immediately after triggering the event, because they won't be available yet.


Of course, you could store the promise object returned by .getPlaces() somewhere and access it elsewhere after you call .trigger(), but that's not a very good idea, as it introduces a side effect of altering external state, which makes for code that is difficult to test, debug and maintain. Steer clear of it if you can.

GregL
  • 37,147
  • 8
  • 62
  • 67