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!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!