2017-05-29 81 views
3

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

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

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

这里是我的代码

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

你可能想看看我们如何在Node.js(或一般的JavaScript)中使用async/await和promise。 这里有一个小小的介绍: https://blog.readme.io/using-async-await-in-node-js-7-6-0/ – LongHike

+0

令人敬畏的线条,'我来自一个PHP背景,一切都是简单的,程序化的,一个接一个的。“喜欢它。 – anwerj

回答

0

您可以使用回调或承诺 您可以使用异步模块或互斥

如果您需要序列化一些异步函数,你可以使用这个方法:

Callback

Native promises

Bluebird promise

Async module

回调和无极大多用于所述第二功能需要第一功能.bluebird相关函数是用于创建承诺和其上具有全定制的模块。

异步模块是运行异步函数并获得结果的好方法。

最后的办法是互斥,如果你有在单个对象的异步写入或文件,你需要锁定释放方法

-1

您可以通过nsynjs同步运行的代码。您的代码可以转换这样的:

第1步:总结与缓慢回调函数到nsynjs感知包装:

// 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; 

第2步:把你的同步逻辑为功能,使用包装从上面执行的功能缓慢:

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

第3步:通过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'); 
    }) 
}); 

请在这里看到更多的例子:https://github.com/amaksr/nsynjs/tree/master/examples/node-module-loading