我正在尝试准备一个通用函数,该函数将允许我在任何数据库/集合上使用任何函数。我不确定即时通讯是否正确执行。这是我在node.js中的功能代码:
function use_db(db_url, func, ...args) {
let prom;
// noinspection JSIgnoredPromiseFromCall
var lele = MongoClient.connect(db_url, (error, client) => {
console.log('Connected');
const db = client.db();
console.log(db);
prom = func(db, ...args);
client.close();
console.log('Disconnected successfully');
});
console.log(lele, 'whaat?');
return prom;
}
我希望它返回值prom
,但这会发生:
第一个输出为console.log(lele, 'whaat?');
,其值为undefined 'whaat?'
然后'Connected'
最后一个是'Disconnected successfully'
因此很明显,目前尚未定义prom
为什么输出按此顺序?为什么console.log(lele, 'whaat?');
首先运行?
有什么想法可以改进此功能,以便它将使用任何其他功能在特定的mognoDB数据库上工作吗?
编辑://
function connectDB(db_url) {
return new Promise((res, rej) => {
MongoClient.connect(db_url, (error, client) => {
if (error) return rej(error);
console.log('Connected');
const db = client.db();
return res({
db,
client
});
});
});
}
async function use_db(db_url) {
console.log('Start');
const {
db,
client
} = await connectDB(db_url);
console.log('After db connection');
return [db, client];
}
let temp_list = use_db(db_url);
const db = temp_list[0];
const client = temp_list[1];
let no_user = can_create_user(db, temp_email);
if(no_user) {
//some code
}
如何保持与数据库的活动连接,并每次都使用db
来执行其他功能?它不等待承诺解决
答案 0 :(得分:0)
Node.js是异步的,它不等待任何阻止程序操作。 check this
function connectDB(db_url) {
return new Promise((res, rej) => {
MongoClient.connect(db_url, (error, client) => {
if (error) return rej(error);
console.log('Connected');
const db = client.db();
return res({
db,
client
});
});
});
}
async function use_db(db_url, func, ...args) {
console.log('Start');
try {
const {
db,
client
} = await connectDB(db_url);
console.log('After db connection');
const prom = func(db, ...args);
client.close();
console.log('Disconnected successfully');
return prom;
} catch (error) {
console.log(error);
}
}
答案 1 :(得分:0)
好的,我只是解决了这个问题,并将其合并为几个函数,每个函数都连接到mongo,然后断开连接。我放弃。这是一个将用户添加到我的数据库的工作示例。
function add_user(db_url, name, surname, email, password) {
MongoClient.connect(db_url, { useNewUrlParser: true }, (error, client) => {
const db = client.db();
db.collection('users').find({email: email}).toArray(function(err, result) {
if(result.length === 0) {
console.log('Adding new user');
insert_into_users(db, name, surname, email, sha256(password));
} else {
console.log('E-mail already in database');
}
client.close();
});
});
}
function insert_into_users(db, name, surname, email, password) {
db.collection('users').insertOne({
name: name,
surname: surname,
email: email,
password: password,
liked_films: []
});
console.log('New user created');
}