我是Node.js的新手,我试图创建非阻塞业务,因为移动客户端可以在mysql服务器上进行CRUD操作(实时)。我知道,我必须添加回调函数,但是如何?有人向我解释回调是什么?如何修复我的代码到非阻塞:
var node_port = 3030;
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var db = require('mysql');
var db_pool = db.createPool({
host : 'localhost',
user : 'root',
password : '1234',
database : 'test',
port : 3306
});
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use( bodyParser.urlencoded() ); // to support URL-encoded bodies
app.post('/api/db', function(objRequest, objResponse) {
objResponse.setHeader('content-type', 'application/json');
db_pool.getConnection(function(objError, objConnection){
if(objError){
sendError(objResponse, 503, 'error', 'connection', objError); //503 - Service Unavailable
}else{
var strQuery = "";
var tableName = objRequest.body.table_name;
switch(objRequest.body.type){
case 'select':
strQuery = "SELECT * FROM "+tableName;
break;
case 'insert':
var id = objRequest.body.id;
var name = objRequest.body.name;
strQuery = "INSERT INTO "+tableName+" (ID, Name) VALUES ('"+id+"','"+name+"')";
break;
case 'update':
var id = objRequest.body.id;
var name = objRequest.body.name;
strQuery = "UPDATE "+tableName+" SET ID='"+id+"' AND Name='"+name+"'";
break;
case 'delete':
var id = objRequest.body.id;
strQuery = "DELETE * FROM "+tableName+" WHERE ID='"+id+"'";
break;
default:
sendError(objResponse, 503, 'error', 'content-type unknown', { code : 'CONTENT-TYPE MISMATCH' });
}//switch
objConnection.query(strQuery, function(objError, objRows, objFields){
if(objError){
sendError(objResponse, 500, 'error', 'query', objError);
}else{
objResponse.send({
results : 'success',
err : '',
err_type : '',
fields : objFields,
rows : objRows,
length : objRows.length
});
}
});
objConnection.release();
}
});
});
function sendError(objResponse, iStatusCode, strResult, strType, objError){
objResponse.send({
results : strResult,
err : objError.type,
err_type : strType
});
}
app.listen(node_port);
console.log('App listening on port' + node_port);