A
A
Alastor2015-02-24 23:12:02
JavaScript
Alastor, 2015-02-24 23:12:02

How to make a synchronous call?

I started trying server-side JavaScript, with the Express framework, and I was too lazy to write routes each time and wrote a wrapper for it so that all calls from app.get and app.post go to psycho.router, and then it checks whether there is one module and whether it has such a method. If there is, then a method is called that returns data, and then the template is immediately picked up where this data is displayed.

var psycho = {
  syncConfig: function() {	},
  language: function(language) { return config.languages.indexOf(language) != -1;},
  method: function(module,method) {return typeof module[method] === "function";},
  loadModule: function(module) {
    try {
      return require('./modules/' + module + '.js');
    } catch(err) {
      return false;
    }
  },
  render: function(controller,template,layout,vars) {
    var content = swig.renderFile('views/' + (controller[0].toUpperCase() + controller.slice(1)) + '/' + template + '.html',vars);
    return swig.renderFile('views/Layout/' + layout + '.html',merge({content:content},vars));
  },
  _404_: function(vars) {
    return this.render('Elements','404','elements',
      merge(
        vars,
        {
          title: __('404 Страница не найдена') + config.other.head.titlePostfixFull,
          keywords: __('404, страница не найдена'),
          description: __('Страница не найдена')
        }
        
      )
    );
  },
  router: function(type,req,res) {
    if (config.checkip && config.allowip.indexOf(req.connection.remoteAddress) == -1) {
          res.status(200).send("look at my horse my horse is amazing");
      } else {   	
      	var url = req.url.split('/');
      	var url = url.slice(1,url.length + 1);
      	
      	if(req.url == '/') {
        	res.status(200).send(this.render(config.defaultRoute[0],config.defaultRoute[1],config.defaultLayout,
        		merge(this.loadModule(config.defaultRoute[0])[config.defaultRoute[1]](req,res),{
        				lang: ['/' + config.defaultLanguage, config.defaultLanguage],
        				robots: config.other.head.robots,
          		}
        		)
        	));
      	} else if(this.language(url[0])) {
      		if (url[1] == undefined) {
        		res.status(200).send(this.render(config.defaultRoute[0],config.defaultRoute[1],config.defaultLayout,
              merge(this.loadModule(config.defaultRoute[0])[config.defaultRoute[1]](req,res),{
                lang: ['/' + url[0], url[0]],
                robots: config.other.head.robots
              }
            )
          ));
      		} else {
        		var module = this.loadModule(url[1]);
      			if (!module) {
      				res.status(404).send(this._404_({lang: ['/' + url[0],url[0]]}));
      			} else {
      				if (url[2] == undefined) {
          			if (this.method(module,'main')) {
          				res.status(404).send(this._404_({lang: ['/' + url[0],url[0]]}));
          			}
        			} else {
        				if (this.method(module,url[2])) {
        					res.status(200).send(this.render(url[1],url[2],config.defaultLayout,merge(module[url[2]](req,res),{
                      lang: ['/' + url[0], url[0]],
                      robots: config.other.head.robots,
                    }
                  )
                ));	    					
        				} else {
        					res.status(404).send(this._404_({lang: ['/' + url[0],url[0]]}));
        				}
        			}
      			}
       		}
      	} else {
        res.status(404).send(this._404_({
      			lang: ['/' + config.defaultLanguage,config.defaultLanguage]
        }));  	
     	 	}
      }
      res.end();
  }
    };
    
    app.get('*', function(req, res) { 
    psycho.router('get', req, res);
  });
  app.post('*', function(req,res) {
    psycho.router('post', req, res);
  });


var LanguageWord = sequelize.define('LanguageWord', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  phrase: {
        type: Sequelize.STRING(256),
        allowNull: false,
        unique: true,
    }
});

global.modelLink = function() { // просто так
  return LanguageWord;
};

I got tired of writing requests by hand and decided to use ORM - Sequelize.js
, so that's what it's about.
I access /ru/admin/users,
respectively, admin.js is pulled up and the user method is executed
module.exports = {
  users: function(req,res) {
    var LanguageWord = modelLink();
      
    console.log("\n\n\n\n\n");
    console.log("START QUERY");
    console.log(LanguageWord.findAll().then(function(word) {
      
      var results = [];
      for(var i = 0; i < word.length; i++) {
        results.push(word[i].dataValues);
      }
      return results;
      console.log("THEN QUERY");
    }));
    console.log("END QUERY");
    console.log("\n\n\n\n\n");
    return  {
      title:	__('Пользователи') + res.locals.head.titleDelimiterSpaces + __('Админ-панель') + res.locals.head.titlePostfixFull,
    };
  },
};

but return fires before the response from the base arrives. Yes, it's basically logical.
please give an elegant example of how to wait for one request and several, and from it to transfer data to this returned object that contains the title
Yes, I know about node-sync, I read a dozen topics, but I still don’t understand how to wait for a response.
if I didn’t write this wrapper that I cited above, then everything could be organized using callbacks, but what is what is.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Prozorov, 2015-02-25
@Alastor

please give an elegant example of how to wait for the execution of one request and several, and transfer data from it

async.js ( https://github.com/caolan/async ) - makes working with callbacks easier. But it has a fatal flaw, it is for asynchronous operation. This module introduces some great features for handling sequential tasks (methods like *Series, waterfall), but `sequential` does not mean `synchronous`.
In general, for your question. Express treats requests like streams. You cannot work in Node with a thread synchronously. Synchronous code you stupidly block the event loop.
You yourself came up with a bicycle with square wheels and now you are asking how to make it so that you can ride it.
Where is the place for synchronous code in a Node.js application that works with I / O streams? Answer: in the initialization area.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question