Answer the question
In order to leave comments, you need to log in
How to write a function to get a user?
Hello. I want to write a function that takes a database, a user id, a collection and returns the user as an object. Due to the asynchrony of the node, nothing happens. How to fix?
function getUser(db, id, collection) {
let a;
db.open(function(err, db) {
if (err) throw err;
let users = db.collection(collection);
let cursor = users.find({telegramId:id});
a = cursor;
cursor.toArray(function(err, results) {
if (err) throw err;
db.close();
});
});
return a;
};
Answer the question
In order to leave comments, you need to log in
Since you are already using ES6 (let), then use promises:
function proxy(fn, ...args) {
return new Promise((res, rej) => {
fn(...args, (err, result) => {
if (err) rej(err);
else res(result);
});
});
}
function getUser(db, id, name) {
var _db;
var result = proxy(db.open.bind(db)).then(db => {
_db = db;
var collection = db.collection(name);
var cursor = collection.find({
telegramId: id
});
return proxy(cursor.toArray.bind(cursor))
}).catch(err => {
console.error(err);
_db.close();
});
result.then(() => _db.close());
return result;
}
getUser(db, 'user-1', 'users').then(arr => {
console.log('users: ', arr);
});
// подключаем npm-библиотеку co
var co = require('co');
function proxy(fn, ...args) {
return new Promise((res, rej) => {
fn(...args, (err, result) => {
if (err) rej(err);
else res(result);
});
});
}
function getUser(db, id, name) {
var _db;
var result = proxy(db.open.bind(db)).then(db => {
_db = db;
var collection = db.collection(name);
var cursor = collection.find({
telegramId: id
});
return proxy(cursor.toArray.bind(cursor))
}).catch(err => {
console.error(err);
_db.close();
});
result.then(() => _db.close());
return result;
}
// основная работа приложения будет тут
co(function*() {
var users = yield getUser(db, 'user-1', 'users');
console.log('users: ', users);
}).catch(err => {
console.error('Произошла страшная ошибка!', err);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question