duanguai2781
2017-05-29 16:23
浏览 87
已采纳

如何控制NodeJS中的应用程序流

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

图片转代码服务由CSDN问答提供 功能建议

我正在nodeJS中编写我的第一个应用程序。 我正在写一个电报机器人,我想知道如何控制应用程序的流程,因为它具有异步性质。 我来自php背景,其中一切都很简单,程序化,一个接一个。

让我们说,在我的机器人中,当收到任何消息时,首先程序必须确保用户 在继续之前,详细信息位于缓存或数据库中。 检查完成后,它可以继续。

我打算通过使用变量作为标志来实现这一点,但由于javascript的异步性质,它无法完成。 我不知道该怎么做。 我是否将侦听器分配给一个对象并发出事件来控制流?

这是我的代码

  const fs = require('  fs'); 
 
 //建立与缓存和数据库的连接
const mysql = require('mysql-wrapper'); 
const Memcached = require('memcached'); 
 nconst memcached = new Memcached('localhost:  11211'); 
 nstst bb = require('bot-brother'); 
 
var settings = {
 host:'localhost',
 database:'test',
 user:'root',
  }; 
var qb = require('node-querybuilder')。QueryBuilder(settings,'mysql','single'); 
 
 //加载数据库缓存函数
const dbc = require(“./ dbc”  ); 
dbc.memcached = memcached; 
dbc.mysqc = qb; 
 
 //加载用户处理函数
const user = require(“./ user”); 
user.dbc = dbc; 
 \  nconst bot = bb({
 key:'331263599:AAHmLl4Zcg4sKGnz7GNzacgkJl1W8lwz33c',
 polling:{interval:0,timeout:1} 
}); 
 
 //用于检查缓存/数据库中用户是否存在的代码 nbot.api.on('message',(msg)=&gt; {
 console.log(msg.from); 
 var userData  = msg.from; 
 var tid = userData.id; 
 //检查用户是否在缓存中
 user.check_user_existence(tid,function(re){
 if(re&lt;  2){
 user.complete_user_existence(re,userData,function(err,response){
 if(err){
 bot.api.sendMessage(tid,“抱歉发生意外错误!”); 
}  else {
 console.log('ha'); 
 play = 1; 
} 
}); 
} 
 
}); 
}); 
 
 
 // 检查
 nif(play == 1){
 send_another_message(); 
 do_some_things(); 
} 
   
 后运行的代码
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douwu5009 2017-05-29 17:28
    已采纳

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

    If you need serialize some asynchronous functions you can use one of this approaches:

    Callback

    Native promises

    Bluebird promise

    Async module

    Callback and Promise mostly used for related functions which second function needs first function .bluebird is a module for creating promises and having full customize on it.

    Async module is good way to run functions asynchronous and get result of them together.

    Last way is Mutex if you had asynchronous write in single object or file you need lock-release approach

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongzhanlian6289 2017-05-29 17:38

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

    Step 1. Wrap slow functions with callbacks into nsynjs-aware 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. Put your synchronous logic into function, use wrappers from above to execute 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');
        })
    });
    

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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题