1

I have a some problem about EventSource. I can easily fetch data, for example I can write the data to console. However, I want to have this data returned from this function. Its not returning, because there is some delay and it returns undefined.

function fetchData(date,lang) {
    var source = new EventSource(*URL*.php?sse=y&lang=" + lang + "&date=" + date);
    source.addEventListener('message', function (e) {
        return e;
    }, false);
}

How can I do that?

Michael
  • 3,093
  • 7
  • 39
  • 83
ceyhunmelek
  • 21
  • 1
  • 5
  • That's the problem with asynchronous events. You should look into callback's to avoid returning a value and having it possibly be undefined. – Michael Apr 04 '18 at 19:14
  • `EventSource` opens a persistent connection; if you want to fetch data once, use `fetch()`. As for handling the response, all code that needs it goes into the callback function. Doing this synchronously is possible but should be avoided because it freezes up the tab. –  Apr 04 '18 at 19:18
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  Apr 04 '18 at 19:19

1 Answers1

0

If it is a one-off request for data, then using EventSource is the wrong tool for the job. EventSource/SSE is to send messages to the client (your browser) as and when they become available on the server. The data messages will come through asynchronously, because nothing else makes sense.

You could wrap your event listener in a promise, which your fetchData() returns, and have it resolve the promise each time it receives a message. I'm not actually sure what would happen when the second message is received.

If it is just a one-off request, then you should instead use an AJAX request. Again, that is asynchronous. There are some suggestions to make that behave as if it is synchronous here, but, as they emphasize there, really you should try to adapt your code to work with the asynchronous nature of it.

Darren Cook
  • 27,837
  • 13
  • 117
  • 217