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