Search code examples
node.jsasynchronoussynchronized

How could I force the execution of a function in Node.js?


I'm making a website in which I could learn the flags from all around the world. The idea is before the front is loaded, my back choose a random int, and pick a flag at this id from my database, and then display it in order then to try to guess the flag.

My problem is that my render is executed before my function which choose a random flag, so I can't display it.

How could I force the getRandomFlags function to be executed before the render of my ejs ? Is that really possible due to the Node.js principe or is there solutions ?

var maxIdDB;
var paysChoisi;

router.post('/', function (req, res) {
    res.render("index.ejs",{extension: 'be.png'});
});

router.use('/', function (req, res) {
    getRandomFlag();
    res.render("index.ejs",{extension: 'fr.png'});
    console.log('test');
});

function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}

function getRandomFlag() {

    db.get('SELECT MAX(id) FROM Flags;', (err, row) => {
        maxIdDB = row['MAX(id)'];
    })

    var randomInt = getRandomInt(maxIdDB);

    const statement = db.prepare('SELECT * FROM Flags WHERE id=?;');
    statement.get(randomInt, (err,result) => {
        setCountry(result);
    });
}

function setCountry(result) {
    paysChoisi = result;
    console.log('set');
}

I tried to load it anyway and refresh several times until my paysChoisi variable is defined but server and client were out of sync. I mean :

server : choose Japan

server : choose France client : answered Japan

server : choose Kenya client : answered France


Solution

  • The easiest solution here would be to use a callback

    router.use('/', function (req, res) {
        getRandomFlag(() => {
          res.render("index.ejs",{extension: 'fr.png'});
          console.log('test');
        });
    });
    
    function getRandomFlag(callback) {
    
        db.get('SELECT MAX(id) FROM Flags;', (err, row) => {
            maxIdDB = row['MAX(id)'];
        })
    
        var randomInt = getRandomInt(maxIdDB);
    
        const statement = db.prepare('SELECT * FROM Flags WHERE id=?;');
        statement.get(randomInt, (err,result) => {
            setCountry(result);
            callback()
        });
    }
    

    But it would be better if you would use promises