Monday, 17 April 2017

How to run a code only after query has finish?

I have the following code:

var userFound = false;

let sql = `SELECT box_id, cubby_id, comport, deliveredToUser
           FROM recipients
           WHERE package_password = ?`;

connection.query(sql, [req.session.sessionUserPackagePassword], function(err, rows, fields) {
    if (!err) {


        for (var i = 0; i < rows.length; i++) {
            // Make the comparaison case insensitive

            if ((rows[i].deliveredToUser).toLowerCase() == `no`) {
                userFound = true;
                console.log(userFound);



                var comport = rows[i].comport;
                var command = "open" + rows[i].cubby_id;
                var commandClose = "close" + rows[i].cubby_id;
                var commandStatus = "status" + rows[i].cubby_id;



                console.log(command);
                console.log(comport);


                var options = {
                    scriptPath: 'python/scripts',
                    args: [command, comport, commandClose, commandStatus] // pass arguments to the script here

                };


                PythonShell.run('controlLock.py', options, function(err, results) {
                    if (err) {
                        res.render('errorConnection', {});
                    }
                    console.log('results: %j', results);
                });

            }



        }

        console.log(userFound);


        // If the query fails to execute
    } else {
        console.log('Error while performing Query.');
        res.render('errorConnection', {});

    }


});
connection.end();

if (!userFound) {
    //
    res.render('pickup/errorAlreadyDelivered', {});
    connection.end();
}

I would want this part at the end to be run only once the query has finish

if (!userFound) {
    //
    res.render('pickup/errorAlreadyDelivered', {});
    connection.end();
}

  console.log("connection ended " + userFound);

I place a console.log outside of the query and at the bottom and despite the query value changing to true it prints out false first, and comes out first because the console.log didn't wait until the query has finish to be able to store the value.



via John

No comments:

Post a Comment