T
T
thevalakas2017-06-19 09:41:05
JavaScript
thevalakas, 2017-06-19 09:41:05

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;
};

The balance function returns undefined, which is supposed to return a balance. console.log from callback returns 100 and not undefined.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
viaskit, 2017-06-19
@thevalakas

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) => {
    // Что то пошло не так :(
})

Second option
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);
});

A
Alexander N++, 2017-06-19
@sanchezzzhak

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 question

Ask a Question

731 491 924 answers to any question