- Node.js Web Development
- David Herron
- 894字
- 2021-06-25 21:54:02
Node.js, ECMAScript 2015/2016/2017, and beyond
In 2015, the ECMAScript committee released a long-awaited major update of the JavaScript language. The update brought in many new features to JavaScript, such as Promises, arrow functions, and Class objects. The language update set the stage for improvements. since that should dramatically improve our ability to write clean, understandable JavaScript code.
The browser makers are adding those much-needed features, meaning the V8 engine is adding those features as well. These features are making their way into Node.js starting with version 4.x.
To learn about the current status of ES-2015 in Node.js, visit https://nodejs.org/en/docs/es6/.
By default, only the ES-2015/2016/2017 features that V8 considers stable are enabled by Node.js. Further features can be enabled with command-line options. The almost-complete features are enabled with the --es_staging option. The website documentation gives more information.
The Node green website (http://node.green/) has a table listing the status of a long list of features in Node.js versions.
The ES2017 language spec is published at:
https://www.ecma-international.org/publications/standards/Ecma-262.htm.
The TC-39 committee does its work on GitHub https://github.com/tc39.
The ES-2015 features make a big improvement in the JavaScript language. One feature, the Promise class, should mean a fundamental rethinking of common idioms in Node.js programming. In ES-2017, a pair of new keywords, async and await, will simplify writing asynchronous code in Node.js, and it should encourage the Node.js community to further rethink the common idioms of the platform.
There's a long list of new JavaScript features, but let's quickly go over two of them that we'll use extensively.
The first is a lighter-weight function syntax called the arrow function:
fs.readFile('file.txt', 'utf8', (err, data) => { if (err) ...; // do something with the error else ...; // do something with the data });
This is more than the syntactic sugar of replacing the function keyword with the fat arrow. Arrow functions are lighter-weight as well as being easier to read. The lighter weight comes at the cost of changing the value of this inside the arrow function. In regular functions, this has a unique value inside the function. In an arrow function, this has the same value as the scope containing the arrow function. This means that, when using an arrow function, we don't have to jump through hoops to bring this into the callback function because this is the same at both levels of the code.
The next feature is the Promise class, which is used for deferred and asynchronous computations. Deferred code execution to implement asynchronous behavior is a key paradigm for Node.js, and it requires two idiomatic conventions:
- The last argument to an asynchronous function is a callback function, which is called when an asynchronous execution is to be performed
- The first argument to the callback function is an error indicator
While convenient, these conventions resulted in multilayer code pyramids that can be difficult to understand and maintain:
doThis(arg1, arg2, (err, result1, result2) => { if (err) ...; else { // do some work doThat(arg2, arg3, (err2, results) => { if (err2) ...; else { doSomethingElse(arg5, err => { if (err) .. ; else ..; }); } }); } });
Depending on how many steps are required for a specific task, a code pyramid can get quite deep. Promises will let us unravel the code pyramid and improve reliability, because error handling is more straightforward and easily captures all errors.
A Promise class is created as follows:
function doThis(arg1, arg2) { return new Promise((resolve, reject) => { // execute some asynchronous code if (errorIsDetected) return reject(errorObject); // When the process is finished call this: resolve(result1, result2); }); }
Rather than passing in a callback function, the caller receives a Promise object. When properly utilized, the preceding pyramid can be coded as follows:
doThis(arg1, arg2) .then(result => {
// This can receive only one value, hence to
// receive multiple values requires an object or array return doThat(arg2, arg3); }) .then((results) => { return doSomethingElse(arg5); }) .then(() => { // do a final something }) .catch(err => { // errors land here });
This works because the Promise class supports chaining if a then function returns a Promise object.
The async/await feature implements the promise of the Promise class to simplify asynchronous coding. This feature becomes active within an async function:
async function mumble() {
// async magic happens here
}
An async arrow function is as follows:
const mumble = async () => {
// async magic happens here
};
It's used as so:
async function doSomething(arg1, arg2, arg3, arg4, arg5) {
var { result1, result2 } = await doThis(arg1, arg2);
var results = await doThat(arg2, arg3);
await doSomethingElse(arg5);
// do a final something
return finalResult;
}
Isn't this a breath of fresh air compared to the nested structure we started with?
The await keyword is used with a Promise. It automatically waits for the Promise to resolve. If the Promise resolves successfully then the value is returned, and if it resolves with an error then that error is thrown. Both handling results and throwing errors are handled in the natural manner.
This example also shows another ES2015 feature: destructuring. The fields of an object can be extracted using the following:
var { value1, value2 } = {
value1: "Value 1", value2: "Value 2", value3: "Value3"
};
We have an object with three fields, but extract only two of the fields.
- 數(shù)據(jù)庫程序員面試筆試真題與解析
- Apache ZooKeeper Essentials
- Maven Build Customization
- Azure IoT Development Cookbook
- Java FX應(yīng)用開發(fā)教程
- Architecting the Industrial Internet
- Hands-On JavaScript High Performance
- 學(xué)習(xí)OpenCV 4:基于Python的算法實(shí)戰(zhàn)
- Mastering Linux Security and Hardening
- 區(qū)塊鏈項(xiàng)目開發(fā)指南
- jQuery技術(shù)內(nèi)幕:深入解析jQuery架構(gòu)設(shè)計(jì)與實(shí)現(xiàn)原理
- Learning Grunt
- Android Studio開發(fā)實(shí)戰(zhàn):從零基礎(chǔ)到App上線 (移動開發(fā)叢書)
- Python機(jī)器學(xué)習(xí)與量化投資
- Mapping with ArcGIS Pro