Phillip R Phillip R - 5 months ago 19
Node.js Question

How to wait for function to finish in express route

I have this route:

app.get("/api/current_user", (req, res) => {

//This function takes 3~ seconds to finish
someObj.logOn(data => {
someObj.setData(data);
});

//This will return before function finishes
return res.send(someObj.data);
});


Here is the .logOn() function (simplified):

logOn(_callback) {
//has some data
var info = {};

//returns data in callback
_callback(info);
}


Question: Is there some way to to wait for the function to finish before returning? This function does not deal with promises, so I cannot use async/await. I couldnt find any good answers, and anything with waiting either had to deal with promises or setTimeout. Both of which would not work, right?

Note: If I put the return statement inside the callback right under
someObj.setData(data);
I will get an error like this:


can't set headers after they are sent


This error occurs not on the intial route load, but after I refresh one more time.

Answer Source

Use a callback. Changing res.send to res.end so that no headers are set. It seems that something is written to the response in the functions we can't see.

 app.get("/api/current_user", (req, res) => {

    //This function takes 3~ seconds to finish
    someObj.logOn(data => {
      someObj.setData(data);
      res.end(JSON.stringify(data));
    });
  });