用nodejs写了一个连接mysql的模块db.js
const mysql = require('mysql'); const pool = mysql.createPool({ connectionLimit : 10, host : 'localhost', user : 'root', password : 'root', database : 'mydb' }); let db = {}; db.q = function (sql,params) { return new Promise((resolve,reject) => { // 取出链接 pool.getConnection(function(err, connection) { if (err) { reject(err); return; } connection.query(sql,params, function (error, results, fields) { // 释放连接 connection.release(); if(err){ reject(err); return; } resolve(results); }); }); }) } module.exports = db;
想测试一下是否联通,就写了个test.js
const db = require('../models/db.js'); let a = await db.q('select * from users',[]); console.log(a);
但是运行是提示错误。如下:
D:wordspace est.js:2 let a = await db.q('select * from users',[]); ^^ SyntaxError: Unexpected identifier at createScript (vm.js:80:10) at Object.runInThisContext (vm.js:139:10) at Module._compile (module.js:599:28) at Object.Module._extensions..js (module.js:646:10) at Module.load (module.js:554:32) at tryModuleLoad (module.js:497:12) at Function.Module._load (module.js:489:3) at Function.Module.runMain (module.js:676:10) at startup (bootstrap_node.js:187:16) at bootstrap_node.js:608:3
思不得其解,经反复搜索,发现db.js返回的是一个pormise对象,自己用await来接的话,就应当有一个async函数。于是重写测试案例。问题解决
const db = require('../models/db.js'); fn = async ctx => { let user = await db.q('select * from users',[]); console.log(user); } fn();
测试结果:
D:wordspace est.js [ RowDataPacket { id: 1, username: 'zhangsan', passward: '123456' }, RowDataPacket { id: 2, username: 'lisi', passward: '234567' } ]
可见异步函数,测试例子是不同,要注意。