2017-05-29 86 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