The main application scenario of Jscex is "JavaScript asynchronous programming", but there is no limit on whether to run on the browser or server. Recently, Node. js is very popular and has just released the Native Windows version. Many people will use it to make small programs such as websites. At present, the most famous framework for developing websites using Node. js is Express, which is easy to use. Some time ago I saw an article in The CNodeJS community. Some students ported a Python-written ToDo list website to Node. on js, I used the fork project to promote Jscex and changed it to a Jscex-based version. You can compare it. Of course, this website is too simple and I am looking for a more suitable project.
BKJIA recommended topics: Node. js Zone
JavaScript is a language without blocking features, so all kinds of APIs are designed to be asynchronous, which is good for server scalability and client webpage response capabilities, however, you may encounter various problems in programming. For example, in the ToDo example, a simple processing function is written as a callback because the database needs to be queried:
- exports.index = function (req, res, next) {
- db.query('select * from todo order by finished asc, id asc limit 50', function (err, rows) {
- if (err) return next(err);
- res.render('index', { todos: rows });
- });
- };
Db variables are used to operate MySQL databases. The query method is used to pass in SQL statements (parameters may also exist) and provides a callback function to indicate errors or return query results. In the callback, we must determine whether the err exists. If yes, call the next report framework "error ". This is required for each asynchronous operation. Imagine that if there is another query after this query, a nesting and err judgment are required. This is true for every processing function, which is also one of the troubles of asynchronous programming: It is difficult to perform unified Exception Processing, and the processing code must always be scattered everywhere. Accidentally, it becomes a "wild exception ", it is hard to find out.
I made the ToDo website Jscex simple. First, let MySQL query be connected to Jscex (lib \ jscex. mysql. js ):
- exports.jscexify = function (db) {
- db.queryAsync = function () {
- var _this = this;
-
- var args = [];
- for (var i = 0; i < arguments.length; i++) {
- args.push(arguments[i]);
- }
-
- var delegate = {
- onStart: function (callback) {
-
- args.push(function (err, result) {
- if (err) {
- callback("failure", err);
- } else {
- callback("success", result);
- }
- });
-
- _this.query.apply(_this, args);
- }
- };
-
- return new Jscex.Async.Task(delegate);
- }
- }
Generally, it is not necessary to convert an asynchronous interface to Jscex (the most important thing is the onStart function ). There are nearly 30 lines of code, most of which are to support the "variable length" parameter. Therefore, the queryAsync function retains all the parameters used for calling, adds a callback, and calls the query function itself. At this point, you can rewrite the previous index and other processing functions (controllers \ todo. js), for example:
- exports.index = toHandler(eval(Jscex.compile("async", function (req, res) {
-
- var todos = $await(db.queryAsync('select * from todo order by finished asc, id asc limit 50'));
- res.render("index", { todos: todos });
-
- })));
The toHandler function is used to encapsulate a function that "accepts req and res and Returns Task" into a standard processing function that "accepts three parameters of req, res, And next, and provides unified error handling:
- var toHandler = function (asyncFunc) {
- return function (req, res, next) {
- var task = asyncFunc(req, res);
- task.addListener(function () {
- if (task.status == "failed") {
- next(task.error);
- }
- });
- task.start();
- }
- }
I keep the implementation of the original processing functions in todo. js. If you are interested, you can compare the differences between them. Unfortunately, because ToDo is too simple, Jscex has not shown many advantages. For example, there is only one MySQL query in each processing program, with no judgment or loop, let alone combining multiple asynchronous functions to make full use of the IO concurrency capability. Therefore, I have been searching for more complex examples recently, but it seems that many open-source websites use Express are rare. I almost want to write one myself. At present, Nodepad seems to be quite good, and may start with it later.
The ToDo website depends on the Express, ejs, and MySQL drivers. At the same time, I add Jscex as its sub-module. If you want to clone a ToDo code, you can:
- > git clone git://github.com/JeffreyZhao/todo.git
- > cd todo
- > git submodule init
- > git submodule update
- > npm install express ejs mysql
- > node server.js
From now on, I will post a series of articles on Jscex ON THE InfoQ Chinese site, including JavaScript development on the browser side and Node. js development on the server side. Maybe you may still have some questions, for example, why should we use dangerous eval functions, eval and Jscex. compile functions cannot be encapsulated? In fact, after reading my article and having a basic understanding of Jscex, we will find that these are all misunderstandings of Jscex from a "traditional perspective. Jscex's practice is indeed "a different path". Otherwise, I don't know how to make it stand out when the JavaScript asynchronous class library is already full.
Original article: http://blog.zhaojie.me/2011/07/nodejs-express-jscex-demo-website-todo.html