從Node查詢數據庫時,如何將HTTP響應對象傳遞給aysynchronous回調?例如(分貝東西是僞代碼):如何將HTTP響應傳遞給Node.js中的回調?
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
// read from database:
var dbClient = createClient(myCredentials);
var myQuery = 'my query goes here';
dbClient.query(myQuery, callback);
function callback(error, results, response) // Pass 'response' to the callback?
{
if (error === null) {
for (var index in results) response.write(index); // Error
response.end('End of data');
}
else {
response.end('Error querying database.')
}
}
}).listen(1337, "127.0.0.1");
當傳遞response
到回調,節點給出的結果繼續對象沒有方法write
錯誤。
這裏最好的策略是什麼?