mercredi 26 juin 2019

NodeJS (Javascript) Design Patterns to avoid async mess

I'm a bit new working on big projects with JS and I feel it's really hard to keep my code clean with almost everything being async.
I'm creating a lot of Promises and declared almost every function as async and using await on almost every line, and I feel this is not the correct way to manage it.
Example:

var mysql = require('mysql');
module.exports = class MyClass {

async constructor() {
    try{
        await this._initDbConnection();    
    }
    catch(e){
        console.log(e);
    }
}

_initDbConnection(){
    return new Promise(function(resolve, reject){
        this.db = mysql.createConnection({
            host: "localhost",
            user: "root",
            password: "",
            database: 'mydb'
        });
        this.db.connect(function(err) {
            if (err) {
                reject(err);
            }
            else {
                console.log("Connected to MySQL!");
                resolve();
            }
        });    
    });

}   
};

The same for every query, or anything executing async.
It's a really ugly solution.
I mean, if I need something from the DB, I want to connect to the DB in the first line, then execute the query in the second line and then process the results on the third line. With JS to do this I need to create a lot of callbacks or use await on every line???

Aucun commentaire:

Enregistrer un commentaire