0

I am sending data from python Flask (as Server Sent Event) but cant return this data from the function.

if print to console.log it works but if try to return it it says undefined

 let eventSource = new EventSource("/listen");

      function getData() {

        eventSource.addEventListener("online", function (e) {
          data = JSON.parse(e.data);
          let station = data.station;
          let finalData = data.data;
          console.log(finalData);
        });
      }
getData();

finalData is what to return to use it in stream graphics so changing console.log(finalData to return finalData shows undefined in console

  • Your `getData` needs to return a promise. `async function getData() { return new Promise((resolve, reject) => { ...; resolve(finalData)})}` Then you can use `console.log(await getData())` – Ruan Mendes Apr 19 '22 at 21:07
  • @JuanMendes async functions return promises, the `return new promise` is unneeded. – evolutionxbox Apr 19 '22 at 21:09
  • should i use `let eventSource = new EventSource("/listen");` inside my function and use await for it? – user8282183292 Apr 19 '22 at 21:15
  • @evolutionxbox `async` functions means it wraps values into Promises so you don't need to do `return Promise.resolve(value);` However, in this case, I need a custom promise that resolves after an event has fired so this is required. Just like anything else where some data is available in a callback that is not already a Promise callback. – Ruan Mendes Apr 20 '22 at 05:38
  • @JuanMendes ok, but either way, putting async in front of a function which returns a promise is unneeded. – evolutionxbox Apr 20 '22 at 07:00
  • It's not strictly needed, but it signals to the user of your function that it returns a Promise. – Ruan Mendes Apr 20 '22 at 11:04

0 Answers0