Doing an sequential operation in Node.js

gear

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

        }

    })

}

Terry Lennox

You should be able to use async / await for this purpose. If your delete_table / create_table functions return a promise you can await the results of these functions.

I've mocked out the sql functions (as well as process.exit()) for the purpose of demonstration. You can see that the queries will run in order, then the process will exit.

Turns out that sql.connect() and sql.close() will return Promises if no callback is passed. This makes the code much simpler to write.

Node.js code

const tables = {

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

init_environment();

async function init_environment() {

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

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

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

async function delete_table(tables_to_delete) {
    await sql.connect(SQL_CONFIG);
    for (var i = 0; i < tables_to_delete.length; i++) {
        var query = "DROP TABLE IF EXISTS " + tables_to_delete[i];
        await runQuery(query);
    }
    await sql.close();
}

async function create_table(tables_to_create) {
    await sql.connect(SQL_CONFIG);
    
    for (var i = 0; i < tables_to_create.length; i++) {

        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 += ")";
        
        await runQuery(query);
    }
    await sql.close();
}

function runQuery(query) {
     console.log("runQuery: Running query: " + query);
     var request = new sql.Request();
     return request.query(query);
}

Demonstration Snippet

/* Mock code */
const SQL_CONFIG = "Some config"
const sql = { 
   connect(config) {
       return new Promise(resolve => setTimeout(resolve, 1000));
   },
   close() { 
       return new Promise(resolve => setTimeout(resolve, 1000));
   }
}

class Request {
    query(query) {
        return new Promise(resolve => setTimeout(resolve, 500, null, {}));
    }
}

sql.Request = Request;

process = { 
    exit() {
        console.log("Exiting process...");
    }
}

/* End Mock code */

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();

async function init_environment() {

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

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

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

async function delete_table(tables_to_delete) {
    await sql.connect(SQL_CONFIG);
    for (var i = 0; i < tables_to_delete.length; i++) {
        var query = "DROP TABLE " + tables_to_delete[i];
        await runQuery(query);
    }
    await sql.close();
}

async function create_table(tables_to_create) {
    await sql.connect(SQL_CONFIG);
    
    for (var i = 0; i < tables_to_create.length; i++) {
        let lastQuery = i === tables_to_create.length -1;

        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 += ")";
        
        await runQuery(query);
    }
    await sql.close();
}

function runQuery(query) {
     console.log("runQuery: Running query: " + query)
     var request = new sql.Request();
     return request.query(query)
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Doing an sequential operation in Node.js

From Dev

Is making sequential HTTP requests a blocking operation in node?

From Dev

Node Js download operation

From Dev

Doing a series of asynchronous operations in node.js

From Dev

Doing a bitwise operation on bytes

From Dev

Why is Node JS blocking an asynchronous file operation?

From Dev

Waiting for operation to finish in node.js

From Dev

node.js wait for file operation to complete

From Java

Doing a cleanup action just before Node.js exits

From Dev

What's the meaning of doing an && operation on two different operands one pointer to node and other an int type?

From Dev

Doing prediction with RNN on Sequential data in keras

From Dev

Sample node.js doing form handling and processing - in Node.js

From Dev

Node executables not doing anything

From Dev

Node executables not doing anything

From Dev

node.js and express : Sequential execution flow one mongodb query request after another

From Dev

Node.js and Express: How to return response after asynchronous operation

From Dev

Node.js using async.forEach with async operation

From Dev

Manage a long-running operation node.js

From Dev

Node.js crashing automatically by mysql without any operation in it

From Dev

Node.js using async.forEach with async operation

From Dev

cant create file on a server 'EPERM, operation not permitted' Node.js

From Dev

Should I consider a bad practice doing blocking I/O during the application bootstrap? (node.js)

From Dev

Node.js request data event not firing. What am I doing wrong?

From Dev

In Node.JS, by doing require('net'), do you not do require('event')?

From Dev

Getting a HTTP 404 error when doing app.post in Node.js

From Dev

JS - Issue doing a function

From Java

How to melt a dataframe while doing some operation?

From Dev

Doing Math Operation using MVC Razor

From Dev

Doing exponential operation using only addition in Java

Related Related

  1. 1

    Doing an sequential operation in Node.js

  2. 2

    Is making sequential HTTP requests a blocking operation in node?

  3. 3

    Node Js download operation

  4. 4

    Doing a series of asynchronous operations in node.js

  5. 5

    Doing a bitwise operation on bytes

  6. 6

    Why is Node JS blocking an asynchronous file operation?

  7. 7

    Waiting for operation to finish in node.js

  8. 8

    node.js wait for file operation to complete

  9. 9

    Doing a cleanup action just before Node.js exits

  10. 10

    What's the meaning of doing an && operation on two different operands one pointer to node and other an int type?

  11. 11

    Doing prediction with RNN on Sequential data in keras

  12. 12

    Sample node.js doing form handling and processing - in Node.js

  13. 13

    Node executables not doing anything

  14. 14

    Node executables not doing anything

  15. 15

    node.js and express : Sequential execution flow one mongodb query request after another

  16. 16

    Node.js and Express: How to return response after asynchronous operation

  17. 17

    Node.js using async.forEach with async operation

  18. 18

    Manage a long-running operation node.js

  19. 19

    Node.js crashing automatically by mysql without any operation in it

  20. 20

    Node.js using async.forEach with async operation

  21. 21

    cant create file on a server 'EPERM, operation not permitted' Node.js

  22. 22

    Should I consider a bad practice doing blocking I/O during the application bootstrap? (node.js)

  23. 23

    Node.js request data event not firing. What am I doing wrong?

  24. 24

    In Node.JS, by doing require('net'), do you not do require('event')?

  25. 25

    Getting a HTTP 404 error when doing app.post in Node.js

  26. 26

    JS - Issue doing a function

  27. 27

    How to melt a dataframe while doing some operation?

  28. 28

    Doing Math Operation using MVC Razor

  29. 29

    Doing exponential operation using only addition in Java

HotTag

Archive