I have a request handler for a particular route that does something like the following:
function doThing(req, res) {
res.json({ "thing" : "thing", "otherThing": externalModule.someFunction("yay"); });
}
It seems like the result is being send before the "someFunction" call completes, so the "otherThing" JSON is always non-existent. How can I wait for that function to return data before sending a response?
Use callbacks. Example:
externalModule.someFunction = function(str, cb) {
// your logic here ...
// ... then execute the callback when you're finally done,
// with error argument first if applicable
cb(null, str + str);
};
// ...
function doThing(req, res, next) {
externalModule.someFunction("yay", function(err, result) {
if (err) return next(err);
res.json({ "thing" : "thing", "otherThing": result });
});
}