Node asynchronous advanced (2) -- continuous then writing of Promise

Node asynchronous advanced series articles:
node asynchronous advanced (1) -- classic writing of callback function
node asynchronous advanced (2) -- continuous then writing of Promise
node asynchronous advanced (3) -- async writing


to continue the previous task , this time using a promise object instead.

Let's go crazy with then
3rd edition (serial)
var http = require('http');
var fs = require('fs');

http.createServer(function(req,res){
  if (req.url=='/') {
    getTitles (res);
  }
}).listen(80,function(){
  console.log('server start..');
});

function getTitles(res){
  var titles;
  get_file_content('/tpl/title.json') // grab the data file first
  .then(JSON.parse) // Let's do parsing here by the way, let's abuse node's asynchrony! !
  .then( function(value){
    titles = value; // Save the local variable to the previous variable.
    return '/tpl/template.html';//Request then pass parameters to the next file
  }).then(
    get_file_content // grab the template file again
  ).then(function (tmpl){ // tmpl is the output of the previous promise
      formatHtml(titles,tmpl, res); // Calling the function is all done
    }
  ).catch( function (err) {
    hadError(err, res); // Call the function that handles the error.
  });
}

// This is a generic function that reads the file asynchronously
function get_file_content(file)
{
  return new Promise(function (resolve, reject) {
    fs.readFile(__dirname+file, function(err,data){
      if (err) {
        reject(err);
      } else {
        resolve(data.toString() );
      }
    });
  });
}


//This is the main logic of this program. After the template is replaced, the output
function formatHtml(titles,tmpl, res) {
  var html = tmpl.replace('%', ' <li > ' +titles.join('</li > <li >') +' </li > ' );
  res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
  res.end(html);
}

// generic error handler
function hadError(err, res) {
  console.log(err);
  res.end('server error.');
}


My own computer is windows, node8.9, the test passed, if a template file or data file is deliberately deleted, it will give an error in the html output program.

Note that the main point of this writing method is to first define a function that returns a promise object, and then put this function in each then, or not, it will be automatically converted into a promise object by node!

In this way of writing, it is generally desirable to handle errors in one place, as long as an exception is thrown in any place, so just follow the above way of writing and put the catch at the end.

The writing method of the function that returns the promise object is to put the correct output in the resolve.
The output of each then is the input of the next then, and the code is very coherent.

However, this task does not need to obtain the template file, it must be requested at the same time after the data file to speed up the speed, so there is the following code:
Fourth Edition (Concurrency)
var http = require('http');
var fs = require('fs');

http.createServer(function(req,res){
  if (req.url=='/') {
    getTitles (res);
  }
}).listen(80,function(){
  console.log('server start..');
});

function getTitles(res){
  var files = {
    title_fun: function (){
      return get_file_content('/tpl/title.json').then(JSON.parse);
    },
    template_fun:function(){
      return get_file_content('/tpl/template.html');
    }
  };
  Promise.all([files.title_fun(), files.template_fun()]).then(function (results){
      formatHtml(results[0],results[1], res); // According to the textbook, the result order here must be the same as the incoming order of all
    }
  ).catch( function (err) {
    hadError(err, res); // Call the function that handles the error.
  });
}

// This is a generic function that reads the file asynchronously
function get_file_content(file)
{
  return new Promise(function (resolve, reject) {
    fs.readFile(__dirname+file, function(err,data){
      if (err) {
        reject(err);
      } else {
        resolve(data.toString() );
      }
    });
  });
}


//This is the main logic of this program. After the template is replaced, the output
function formatHtml(titles,tmpl, res) {
  var html = tmpl.replace('%', ' <li > ' +titles.join('</li > <li >') +' </li > ' );
  res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
  res.end(html);
}

// generic error handler
function hadError(err, res) {
  console.log(err);
  res.end('server error.');
}



It can be seen that the concurrent requests are faster, make full use of the inherent asynchronous characteristics of node, and make full use of the performance of the computer.
The point of concurrency is to write all(....).then(...) .

Nevertheless, the program is still rather wordy, is there a simpler way to write it? Already have.
Please continue to the next article


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326603038&siteId=291194637