gpt4 book ai didi

javascript - Nodejs 异步/等待 mysql 查询

转载 作者:行者123 更新时间:2023-12-02 21:33:02 25 4
gpt4 key购买 nike

我有一个当前结构如下的nodejs项目,我需要在客户端表上插入一个注册表并从该表返回最后插入的ID,以便我可以在第二个表中使用它,但我需要等到插入在将客户 ID 插入我的第二个表之前,在客户表中完成。我正在尝试使用 async/await,但总是得到空值。

我的 MYSQL 连接:db.model.js

const config = require('config');
const mysql = require("mysql");

const connection = mysql.createConnection({
host: config.get('mysql.host'),
user: config.get('mysql.user'),
password: config.get('mysql.password'),
database: config.get('mysql.database')
});

connection.connect(function (err) {
if (err) {
console.error(`MySQL Connection Error: ${err.stack}`);
return;
}

console.log(`MySQL connected successfully!`);
});

module.exports = connection;

我的客户模型

const mysql = require("./db.model");

const Client = function(client) {
this.login = client.login;
};

Client.create = (newClient, result) => {
mysql.query("INSERT INTO clients SET ?", newClient,
(err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}

result(null, {
id: res.insertId,
...newClient
});
}
);
};

module.exports = Client;

这是客户端 Controller (我尝试在这里使用 async/await)

const Client = require('../models/client.model');

exports.create = (login) => {
const client = new Client({
login: login
});

Client.create(client, async (err, data) => {
if(!err) {
return await data.id;
} else {
return false;
}
});
}

这是另一个 Controller ,我想在其中使用客户端 Controller 中的方法:


const ClientController = require('../controllers/client.controller');

...

utils.connect()
.then(clt => clt.sub.create(data))
.then((sub) => {

let lastInsertedId = ClientController.create(sub.login);

// lastInsertedId always return null here,
// but I know ClientController return a value after some time.
// method below will fail because lastInsertedId cannot be null
TransactionController.transactionCreate(lastInsertedId,
sub.id,
sub.param);
})
.catch(error => res.send(error.response.errors))

感谢任何帮助。

最佳答案

用于创建数据库连接的文件

const config = require('config');
const mysql = require('mysql2');
const bluebird = require('bluebird');

const dbConf = {
host: config.dbhost,
user: config.dbuser,
password: config.dbpassword,
database: config.database,
Promise: bluebird
};

class Database {

static async getDBConnection() {
try {
if (!this.db) {
// to test if credentials are correct
await mysql.createConnection(dbConf);
const pool = mysql.createPool(dbConf);
// now get a Promise wrapped instance of that pool
const promisePool = pool.promise();
this.db = promisePool;
}
return this.db;
} catch (err) {
console.log('Error in database connection');
console.log(err.errro || err);
}

}
}

module.exports = Database;

使用连接来执行 native 查询

const database = require('./database');

let query = 'select * from users';
let conn = await dl.getDBConnection();
let [data, fields] = await conn.query(query);

关于javascript - Nodejs 异步/等待 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60569844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com