Node js asynchron router

Hello, i have a question about Node js router, i want that the router send a answer for the webrequest directly without waiting for some code which is inside a promise block and i am not sure if i have understand asynchron working from nodejs good enough, if my following code would do that:

let objektKunden=[];
app.get('/getuser', async function (req, res)
     new Promise((resolve) => {
      const kundenData = [];
      const masterData = [];

        Kunden.forEach(item => {
          if (item.note !== "master") {
          } else {
      const responseJSON = JSON.stringify(objektKunden);     
  catch (error)
    console.error("error getuser:", error);

My wish is that the router send objektKunden directly as answer and dont wait that the code above which is inside the promise will be run first

Well you can’t return something without first fetching it. So I’m not really sure what’s you’re after here.

Hi @fibonancileonardo the promise callback would still run first, if you want to delay the execution you might use a timeout… but as @rpkamp noted there wouldn’t be much point.

Be super careful though! You’re populating a global customer object here, so if you would actually delay that the first caller would get an empty array, and the second the presumably sensitive data of the former.


I think for what you are looking for is more like a server event. So you can start and subscribe to the server event, which will return immediately and then wait for the message when the fetch is done.

Left or right, you’ll have to wait for a response. There is no way to “wait faster”. You can complicate it as much as you like, but that’ll only make it harder to understand the code, it won’t make an actual difference.

I see the use case for this. If you have to load much data or do a complicated calculation, which would take more then 10 seconds, you should show the user some kind of progress indicator and not only a spinning wheel. And yes, this makes code much more complicated but it’s worse the useability. Sadly this is not very popular nowadays.

Sure, but you can do all of that without SSE.

Then you have to poll for progress. I don’t think this is the better solution.

Well the route in question looks like a mere API endpoint anyway, so I wouldn’t bother with UX here… it just sends a JSON response after all. So just serve a static HTML page that shows a loading indicator of sorts, and fetch the actual /getuser data using AJAX.

1 Like