I'm writing my first application in nodeJS. I'm writing a telegram bot, and i was wondering how to control the flow of the application given it asynchronous nature. I come from a php background where everything was simple, procedural, one after the other.
Lets say, in my bot, when any message is received, first the program must make sure the user details are in the cache or database before proceeding. After the check is done it can proceed.
I was going to do this by using a variable for a flag, but it cannot be done because of the asynchronous nature of javascript. I have no idea how to go about doing this. Do i assign listeners to an object and emit 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();
}
via Haider Ali
No comments:
Post a Comment