Node.js and Express: How to return response after asynchronous operation

后端 未结 1 1364
孤街浪徒
孤街浪徒 2021-02-04 06:46

I\'m new to Node.js, so I\'m still wrapping my head around asynchronous functions and callbacks. My struggle now is how to return a response after reading data from a file in an

相关标签:
1条回答
  • 2021-02-04 07:30

    To access a variable in a different function, when there isn't a shared scope, pass it as an argument.

    You could just pass res and then access both query and send on the one variable within the function.


    For the purposes of separation of concerns, you might be better off passing a callback instead.

    Then do_search only needs to know about performing a query and then running a function. That makes it more generic (and thus reusable).

    searcher.do_search(res.query, function (data) {
        res.send(...);
    });
    
    function do_search(query, callback) {
        callback(...);
    } 
    
    0 讨论(0)
提交回复
热议问题