Node.js 同步问题

Node.js 一些同步的实现方法
最近更新:2019-04-17
Node.js v8.9.0

MySQL

数据库连接

1
2
3
4
5
6
7
8
9
10
11
// mysql.js
const mysql = require('mysql');
const conn = mysql.createConnection({
host : 'localhost',
port : '3306',
user : 'root',
password : '***',
database : '***'
});

conn.connect();

根据查询结果修改 response

首先封装查询操作,添加回调函数(callback)

1
2
3
4
5
6
7
8
9
10
// mysql.js
exports.query = (sql, params, callback) => {
conn.query(sql, params, (err, res) => {
if (err) {
callback(false);
} else {
callback(res);
}
});
}

调用封装的查询操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* ============================ app.js ============================ */
const userManage = require('./app/service/userManage');
// 登录操作
app.post('/signin', async (req, res) => {
let account = req.body.account;
let password = req.body.password;

userManage.signIn(account, password, (result) => {
if (result.success) {
res.json({
success : true,
});
} else {
res.json({
success : false,
message : '账号或密码错误',
});
}
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* ============================ userManage.js ============================ */
var signIn = async (account, password, callback) => {
let sql = 'SELECT password FROM tableName WHERE account=?';
let params = [account];

db.query(sql, params, function(result) {
let success = false;
if (result) {
let info = result[0];
if ( password == info.password ) {
success = true;
callback({success : true,})
}
}

if (!success) {
callback({success:false});
}
});
}
exports.signIn = signIn;