Doing an sequential operation in Node.js

I built myself a helper-function with node.js to prepare a database, where I currently often do changes in the table structure. So I defined my database structure in an global object "tables" and built the tables using the mssql library via sql-queries. All in all it worked out fine so for. But I now added an process.exit(1) to the end of my init function, which showed me that the interpreter runs through the operations without waiting for sql-execution. How can I modify the code, that the interpreter will execute all steps correctly and quit the program afterwards?

const tables = {

    table_name_1: {
        "key1": "nvarchar(25)",
        "key2": "int",
        "..": "bit",
    },
    table_name_2: {
        "key1": "int",
        "key2": "nvarchar(50)",
        "..": "int",
    },
    table_name_3: {
        "key1": "int",
        "key2": "int",
        "..": "int",
    }
    
}

init_environment();

function init_environment() {

    console.log("Init started...");

    delete_table(Object.keys(tables));
    create_table(Object.keys(tables));

    console.log("Init finished");
    process.exit(1);
}

function delete_table(tables_to_delete) {

    sql.connect(SQL_CONFIG, function () {

        for (var i = 0; i < tables_to_delete.length; i++) {

            var request = new sql.Request();
            var query = "DROP TABLE " + tables_to_delete[i];

            request.query(query, function (err, recordset) {
                if (err) {
                    console.log(err);
                } 
            });

        }

    })

}

function create_table(tables_to_create) {

    sql.connect(SQL_CONFIG, function () {

        for (var i = 0; i < tables_to_create.length; i++) {

            var request = new sql.Request();

            var query = "CREATE TABLE " + tables_to_create[i] + " (id INT IDENTITY(1,1) PRIMARY KEY, ";

            for (var key in tables[tables_to_create[i]]) {
                query += key + " " + tables[tables_to_create[i]][key] + ", ";
            }

            query += ")";

            request.query(query, function (err, recordset) {
                if (err) {
                    console.log(err);
                }
            });

        }

    })

}

8 thoughts on “Doing an sequential operation in Node.js”

Leave a Comment