How to manage application flow in NodeJS

I am writing my first application in nodeJS. I am writing a telegram bot and I was wondering how to manage the flow of the application given its asynchronous nature. I came from a php background where everything was simple, procedural, one by one.

Let's say in my bot, when any message is received, the program must first make sure the user data is in the cache or database before proceeding. After completing the check, he can continue.

I was going to do this using a variable for the flag, but it cannot be done due to the asynchronous nature of javascript. I have no idea how to do this. Am I assigning listeners to an object and emitting events to control the flow?

Here is my code

    const fs = require('fs');

// Establish connection with cache and database
const mysql = require('mysql-wrapper');
const Memcached = require('memcached');
const memcached = new Memcached('localhost:11211');
const bb = require('bot-brother');

var settings = {
    host: 'localhost',
    database: 'test',
    user: 'root',
};
var qb = require('node-querybuilder').QueryBuilder(settings, 'mysql', 'single');

//Load the database cache functions
const dbc = require("./dbc");
dbc.memcached = memcached;
dbc.mysqc = qb;

//Load the user handling functions 
const user = require("./user");
user.dbc = dbc;

const bot = bb({
    key : '331263599:AAHmLl4Zcg4sKGnz7GNzacgkJl1W8lwz33c',
    polling: { interval: 0, timeout: 1 }
});

//code that checks user existence in cache/db
bot.api.on('message', (msg)=>{
    console.log(msg.from);
    var userData = msg.from;
    var tid = userData.id;
    //Check if user is in cache 
    user.check_user_existence(tid,function(re){
        if(re < 2){
            user.complete_user_existence(re,userData,function(err,response){
                if(err){
                    bot.api.sendMessage(tid,"Sorry an unexpected error occured!");
                } else {
                    console.log('ha');
                    play = 1;
                }
            });
        } 

    });
});


//Code to be run after checking 
if(play==1){
    send_another_message();
    do_some_things();
}

      

+3


source to share


2 answers


You can use callbacks or promises You can use async module or mutexes

If you need to serialize some of the asynchronous functions, you can use one of the following methods:

Callback

Native promises

the bluebird promise



Asynchronous module

Callback and Promise are most often used for related functions, the second function of which is needed by the first function. Bluebird is a module for creating promises and has full customization on it.

An asynchronous module is a good way to run functions asynchronously and get results from them.

The last way is Mutex if you had an asynchronous write to a single object or file that requires a lock-release approach

0


source


You can run code synchronously via nsynjs . Your code can transform like this:

Step 1. End the slow functions with callbacks in nsynjs compatible wrappers:

// content of wrappers.js
user = require("./user");
exports.user_check_user_existence_wrapper = function (ctx, uid) {
    var res = {};

    user.check_user_existence(tid,function(re){
        res.re = re;
        ctx.resume();
    })

    return res;
};
exports.user_check_user_existence_wrapper.nsynjsHasCallback = true;

exports.user_complete_user_existence_wrapper = function(ctx, re, userData) {
    var res = {};

    user.complete_user_existence(tid,function(error,ue_response){
        res.error = error;
        res.ue_response = ue_response;
        ctx.resume(error); // if error is set, it will cause exception in the caller
    })

    return res;
};
exports.user_complete_user_existence_wrapper.nsynjsHasCallback = true;

      

Step 2. Insert your synchronous logic into a function, use the wrappers on top to do slow functions:



var synchronousCode = function(wrappers,msg) {
    console.log(msg.from);
    var userData = msg.from;
    var tid = userData.id;
    //Check if user is in cache 
    var re = wrappers.user_check_user_existence_wrapper(nsynjsCtx,tid).re;
    if(re < 2)
        try {
            var res = wrappers.user_complete_user_existence_wrapper(re,userData).ue_response;
            console.log('ha');
            play = 1;
        }
        catch (e) {
            bot.api.sendMessage(tid,"Sorry an unexpected error occured!",e);
        };
}

      

Step 3. Run your synchronous function via nsynjs:

var nsynjs = require('nsynjs');
var wrappers = require('./wrappers');
var synchronousCode = function(wrappers,msg) {
....
}

bot.api.on('message', function(msg) {
    nsynjs.run(synchronousCode,{},wrappers,msg,function(){
        console.log('synchronousCode finished');
    })
});

      

See more here: https://github.com/amaksr/nsynjs/tree/master/examples/node-module-loading

-1


source







All Articles