mercredi 3 juin 2015

Nesting mysql statements in node, async.whilst

var i = 0;
async.whilst(
    // test to perform next iteration
    function () {
        return i <= thefooz.length - 1;
    },
    function (innerCallback) {

        //Some calculations, where I get classes and Things variables.

        for (var m = 0; m <= (classes.length - 1); m++) {
            var Myurl = classes[m];
            var MyThing = Things[m];

            (function (Myurl, MyThing) {

                SqlNames = {};

                //First mysql query (check if UrlLink is present or not).
                var query = connection.query('SELECT * FROM mydatabase WHERE UrlLink=? LIMIT 1', [Myurl], function (err, rows, fields) {
                    if (err) throw err;
                    SqlNames = rows;
                    logAll();
                });

                ///
                function logAll() {
                    if (SqlNames.length == false) {
                        console.log("first thing");

                        //Second mysql query (if UrlLink not present, then insert in mydatabase.
                        var post = {
                            UrlLink: Myurl,
                            ThingName: MyThing
                        };
                        var query2 = connection.query('Insert IGNORE INTO mydatabase Set ?', post,
                            function (err, result) {

                                if (err) throw err;

                            });
                    } else if (...) {
                        console.log("Another thing");
                    } else {
                        console.log("Third thing");
                    };
                };

            })(Myurl, TheCar);

            setTimeout(function () {
                i++;
                innerCallback();
            }, 10000);


        }; //Close if statement
    }; //Close innerCallback
); //Close async.whilst

I hope the code above is readable. I am trying to first check if the UrlLink is present in mydatabase, if it is not then I want to Insert it into mydatabase. How do I nest properly? Now I just only get the SELECT statement running, but INSERT never happens.

Aucun commentaire:

Enregistrer un commentaire