node.js - Nodejs request handlers not waiting for function to return -
i have request handler particular route following:
function dothing(req, res) { res.json({ "thing" : "thing", "otherthing": externalmodule.somefunction("yay"); }); }
it seems result being send before "somefunction" call completes, "otherthing" json non-existent. how can wait function return data before sending response?
use callbacks. example:
externalmodule.somefunction = function(str, cb) { // logic here ... // ... execute callback when you're done, // 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 }); }); }
Comments
Post a Comment