官术网_书友最值得收藏!

Optimized JavaScript

The JavaScript language is in constant flux, and some major changes and improvements have begun to find their way into native compilers. The V8 engine used in the latest Node builds supports nearly all of the latest features. Surveying all of these is beyond the scope of this chapter. In this section, we'll mention a few of the most useful updates and how they might be used to simplify your code, helping to make it easier to understand and reason about, to maintain, and perhaps even become more performant.

We will be using the latest JavaScript features throughout this book. You can use Promises, Generators, and async/await constructs as of Node 8.x, and we will be using those throughout the book. These concurrency operators will be discussed at depth in Chapter 2, Understanding Asynchronous Event-Driven Programming, but a good takeaway for now is that the callback pattern is losing its dominance, and the Promise pattern in particular is coming to dominate module interfaces.

In fact, a new method util.promisify was recently added to Node's core, which converts a callback-based function to a Promise-based one:

const {promisify} = require('util');
const fs = require('fs');

// Promisification happens here
let readFileAsync = promisify(fs.readFile);

let [executable, absPath, target, ...message] = process.argv;

console.log(message.length ? message.join(' ') : `Running file ${absPath} using binary ${executable}`);

readFileAsync(target, {encoding: 'utf8'})
.then(console.log)
.catch(err => {
let message = err.message;
console.log(`
An error occurred!
Read error: ${message}
`);
});

Being able to easily promisify fs.readFile is very useful.

Did you notice any other new JavaScript constructs possibly unfamiliar to you?

主站蜘蛛池模板: 通河县| 崇阳县| 射洪县| 东兰县| 汝州市| 曲麻莱县| 郁南县| 合水县| 永城市| 泰宁县| 上饶市| 石楼县| 那坡县| 郁南县| 凉城县| 康定县| 金门县| 哈巴河县| 丽江市| 新巴尔虎右旗| 保定市| 广安市| 宁远县| 陇西县| 阿克苏市| 满洲里市| 文水县| 锡林浩特市| 贺州市| 韶山市| 巴中市| 皋兰县| 卓尼县| 新平| 金昌市| 醴陵市| 长乐市| 门源| 神木县| 稻城县| 四平市|