Reputation: 3956
This may be a really simple question, but I'm not sure what the most accepted way to do this is.
I have a route that makes an API call and then returns the result. The problem is that the route doesn't wait for the API call to finish, but just sends the response immediately.
Seems like I need to structure it so that the response is fired in the callback, but I'm not exactly sure what the best practice is in this case.
app.get('/', function(req, res){
var info = timesheet.getData(); // This function makes API call and
// waits for response, then returns
// data in callback function
res.send(info); // info is undefined since this fires
// before the API response is finished
});
Thanks, you guys are awesome. John
(edited my code to be more straight forward to the question)
Upvotes: 2
Views: 416
Reputation: 124790
does timesheet.getData
accept a callback parameter? I would imagine it does if it is gathering data asynchronously. If it does then yes, just put your res.send
in there like so:
app.get('/', function(req, res) {
timesheet.getData(function(info) {
res.send(info);
}
});
If not then, well, I don't know; I'll just delete this response.
Upvotes: 1