2

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I wrote all of it, so it didn't have a callback, but I did some reading about callback functions and wrote one in after I understood the way they're supposed to work. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.