Home >Web Front-end >JS Tutorial >Let Express support async method sharing

Let Express support async method sharing

小云云
小云云Original
2018-01-26 16:36:291749browse

This article mainly introduces in detail how to make Express support async/await. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

With the release of Node.js v8, Node.js has natively supported async/await functions, and the web framework Koa has also released the official version of Koa 2, which supports async/await middleware. Handling asynchronous callbacks brings great convenience.

Since Koa 2 already supports async/await middleware, why not use Koa directly, but also modify Express to support async/await middleware? Because the official version of Koa 2 was released not long ago, and many old projects still use Express, it is impossible to overthrow them and rewrite them in Koa. This cost is too high, but if you want to use the convenience brought by the new syntax, you can only Express has been transformed, and this transformation must be non-intrusive to the business, otherwise it will cause a lot of trouble.

Use async/await directly

Let us first look at the situation of using async/await function directly in Express.

const express = require('express');
const app = express();
const { promisify } = require('util');
const { readFile } = require('fs');
const readFileAsync = promisify(readFile);
  
app.get('/', async function (req, res, next){
 const data = await readFileAsync('./package.json');
 res.send(data.toString());
});
// Error Handler
app.use(function (err, req, res, next){
 console.error('Error:', err);
 res.status(500).send('Service Error');
});
  
app.listen(3000, '127.0.0.1', function (){
 console.log(`Server running at http://${this.address().address }:${this.address().port }/`);
});

The above does not modify Express, and directly uses the async/await function to process the request. When requesting http://127.0.0.1:3000/, it is found that the request can be requested normally, and the response can also be responded normally. . It seems that you can use the async/await function directly without making any changes to Express. But if an error occurs in the async/await function, can it be handled by our error handling middleware? Now let's read a non-existing file, for example, replace the previously read package.json with age.json.

app.get('/', async function (req, res, next){
 const data = await readFileAsync('./age.json');
 res.send(data.toString());
});

Now when we request http://127.0.0.1:3000/, we find that the request cannot be responded to and will eventually time out. The following error was reported in the terminal:

It was found that the error was not handled by the error handling middleware, but an unhandledRejection exception was thrown. Now if we use try/ catch to manually catch errors?

app.get('/', async function (req, res, next){
 try {
  const data = await readFileAsync('./age.json');
  res.send(datas.toString());
 } catch(e) {
  next(e);
 }
});

It is found that the request is processed by the error handling middleware, which means that it is okay for us to manually and explicitly capture the error, but it is too inconvenient to add a try/catch to each middleware or request processing function. It is elegant, but it is intrusive to the business code, and the code also looks ugly. Therefore, through experiments using async/await functions directly, we found that the direction of transformation of Express is to be able to receive errors thrown in async/await functions without being intrusive to business code.

Modify Express

There are two ways to handle routing and middleware in Express. One is to create an app through Express, add middleware and handle routing directly on the app, as shown below Like this:

const express = require('express');
const app = express();
  
app.use(function (req, res, next){
 next();
});
app.get('/', function (req, res, next){
 res.send('hello, world');
});
app.post('/', function (req, res, next){
 res.send('hello, world');
});
  
app.listen(3000, '127.0.0.1', function (){
 console.log(`Server running at http://${this.address().address }:${this.address().port }/`);
});

The other is to create a routing instance through the Router of Express. Add middleware and process routing directly on the routing instance, like the following:

const express = require('express');
const app = express();
const router = new express.Router();
app.use(router);
  
router.get('/', function (req, res, next){
 res.send('hello, world');
});
router.post('/', function (req, res, next){
 res.send('hello, world');
});
  
app.listen(3000, '127.0.0.1', function (){
 console.log(`Server running at http://${this.address().address }:${this.address().port }/`);
});

These two methods can Mix it up. Now let's think about how to make a function like app.get('/', async function(req, res, next){}) so that the errors thrown by the async function inside can be handled uniformly. Woolen cloth? In order for errors to be handled uniformly, of course, next(err) must be called to pass the error to the error handling middleware. Since the async function returns a Promise, it must be in the form of asyncFn().then().catch. (function(err){ next(err) }), so if you modify it like this, you will have the following code:

app.get = function (...data){
 const params = [];
 for (let item of data) {
  if (Object.prototype.toString.call(item) !== '[object AsyncFunction]') {
   params.push(item);
   continue;
  }
  const handle = function (...data){
   const [ req, res, next ] = data;
   item(req, res, next).then(next).catch(next);
  };
  params.push(handle);
 }
 app.get(...params)
}

In the above code, we judge that the parameters of the app.get() function , if there is an async function, use item(req, res, next).then(next).catch(next); to handle it, so that errors thrown in the function can be captured and passed to the error handling middleware. . However, there is an obvious mistake in this code. It calls app.get() at the end, which is recursive, destroys the function of app.get, and cannot handle the request at all, so it needs to continue to be modified.

We said before that Express's two ways of handling routing and middleware can be mixed, so we will mix these two ways to avoid recursion. The code is as follows:

const express = require('express');
const app = express();
const router = new express.Router();
app.use(router);
  
app.get = function (...data){
 const params = [];
 for (let item of data) {
  if (Object.prototype.toString.call(item) !== '[object AsyncFunction]') {
   params.push(item);
   continue;
  }
  const handle = function (...data){
   const [ req, res, next ] = data;
   item(req, res, next).then(next).catch(next);
  };
  params.push(handle);
 }
 router.get(...params)
}

It seems that after the transformation like above Everything is working properly and requests are being processed normally. However, by looking at the source code of Express, I found that this destroyed the app.get() method, because app.get() can not only be used to process routing, but also be used to obtain the application configuration. The corresponding source code in Express is as follows:

methods.forEach(function(method){
 app[method] = function(path){
  if (method === 'get' && arguments.length === 1) {
   // app.get(setting)
   return this.set(path);
  }
  
  this.lazyrouter();
  
  var route = this._router.route(path);
  route[method].apply(route, slice.call(arguments, 1));
  return this;
 };
});

So during transformation, we also need to do special processing for app.get. In actual applications, we not only have get requests, but also post, put and delete requests, so our final modified code is as follows:

const { promisify } = require('util');
const { readFile } = require('fs');
const readFileAsync = promisify(readFile);
const express = require('express');
const app = express();
const router = new express.Router();
const methods = [ 'get', 'post', 'put', 'delete' ];
app.use(router);
  
for (let method of methods) {
 app[method] = function (...data){
  if (method === 'get' && data.length === 1) return app.set(data[0]);

  const params = [];
  for (let item of data) {
   if (Object.prototype.toString.call(item) !== '[object AsyncFunction]') {
    params.push(item);
    continue;
   }
   const handle = function (...data){
    const [ req, res, next ] = data;
    item(req, res, next).then(next).catch(next);
   };
   params.push(handle);
  }
  router[method](...params);
 };
}
   
app.get('/', async function (req, res, next){
 const data = await readFileAsync('./package.json');
 res.send(data.toString());
});
   
app.post('/', async function (req, res, next){
 const data = await readFileAsync('./age.json');
 res.send(data.toString());
});
  
router.use(function (err, req, res, next){
 console.error('Error:', err);
 res.status(500).send('Service Error');
}); 
   
app.listen(3000, '127.0.0.1', function (){
 console.log(`Server running at http://${this.address().address }:${this.address().port }/`);
});

Now the transformation is complete, we only need to add a small piece of code, You can directly use async function as the handler to handle requests, which is not intrusive to the business. The thrown errors can also be passed to the error handling middleware.

Related recommendations:

NodeJs’s method of handling asynchronous processing through async and await

How to use async functions in Node.js

Detailed explanation of ES6's async+await synchronization/asynchronous solution

The above is the detailed content of Let Express support async method sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn