Answer the question
In order to leave comments, you need to log in
Nodejs sqlite3 why is the query result not being written to a variable?
'use strict';
const sqlite = require('sqlite3').verbose();
const db = new sqlite.Database('database.db');
module.exports.register = function (from) {
db.all("SELECT * FROM users WHERE tele_id = ?", [from.id], function (err, rows) {
if (rows.length < 1) {
if (from.last_name === undefined) {
from.last_name = null;
}
if (from.username === undefined) {
from.username = null;
}
db.run("INSERT INTO users (tele_id, first_name, last_name, username) VALUES (?, ?, ?, ?)", [from.id, from.first_name, from.last_name, from.username]);
}
});
};
module.exports.balance = function (tele_id) {
let balance;
db.get("SELECT * FROM users WHERE tele_id = ?", [tele_id], function (err, result) {
console.log(result.balance); // 100
balance = result.balance; // undefined
});
return balance;
};
Answer the question
In order to leave comments, you need to log in
I'll try and put in my two cents
module.exports.balance = function (tele_id) {
return new Promise((resolve, reject) => {
db.get("SELECT * FROM users WHERE tele_id = ?", [tele_id], (err, result) => {
if (err) {
reject(err);
}
resolve(result)
});
});
}
// Где то в другом месте
balance(123).then((row) => {
// Обработка записи из таблицы
}).catch((err) => {
// Что то пошло не так :(
})
module.exports.balance = function (tele_id, callback) {
db.get("SELECT * FROM users WHERE tele_id = ?", [tele_id], callback);
}
// Где то в другом месте
balance(123, function(err, row) {
if (err) {
throw Error(err);
}
console.log(row);
});
because js is asynchronous
example
your function was called and the code went on to be executed and the result has not yet been received.
it’s all through collback noodles, promises, or any other solutions that solve this await problem
, for example, in es6 you can solve this through the await operator
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question