javascript - Node.js and Express: How to return response after asynchronous operation -
i'm new node.js, i'm still wrapping head around asynchronous functions , callbacks. struggle how return response after reading data file in asynchronous operation.
my understanding sending response works (and works me):
app.get('/search', function (req, res) { res.send("request received"); });
however, want read file, perform operations on data, , return results in response. if operations wanted perform on data simple, -- perform them inline, , maintain access res
object because it's still within scope.
app.get('/search', function (req, res) { fs.readfile("data.txt", function(err, data) { result = process(data.tostring()); res.send(result); }); });
however, file operations need perform long , complicated enough i've separated them out own function in separate file. result, code looks more this:
app.get('/search', function (req, res) { searcher.do_search(res.query); // ??? ??? });
i need call res.send
in order send result. however, can't call directly in function above, because do_search
completes asynchronously. , can't call in callback do_search
because res
object isn't in scope there.
can me understand proper way handle in node.js?
to access variable in different function, when there isn't shared scope, pass argument.
you pass res
, access both query
, send
on 1 variable within function.
for purposes of separation of concerns, might better off passing callback instead.
then do_search
needs know performing query , running function. makes more generic (and reusable).
searcher.do_search(res.query, function (data) { res.send(...); }); function do_search(query, callback) { callback(...); }
Comments
Post a Comment