ES2018 core improvements: asynchronous iteration, Promise.finally(), Rest/Spread attributes and regular expression enhancements
ES2018 (also known as ES9) has brought several important updates to JavaScript. This article will explain these new features and their applications through examples.
JavaScript Standard (ECMAScript) continues to evolve, and after ES6 (ECMAScript 2015), the new annual release process accelerates the iteration of functions. ES2018 was the latest version at that time.
TC39 (Technical Committee 39) is responsible for promoting JavaScript proposals, and the process is as follows:
Main features of ES2018:
1. Asynchronous iteration:
In async/await
, if you try to call an asynchronous function within a synchronous loop, for example:
async function process(array) { for (let i of array) { await doSomething(i); } }
will not work properly. ES2018 introduces an asynchronous iterator, whose next()
method returns a promise, allowing for async operations to be performed in serial using for await ... of
loop:
async function process(array) { for await (let i of array) { doSomething(i); } }
2. Promise. finally():
Promise.finally()
is used to execute the same code after the Promise is completed (whether successful or failed), and is often used for cleaning work:
function doSomething() { doSomething1() .then(doSomething2) .then(doSomething3) .catch(err => { console.log(err); }) .finally(() => { // 完成后的操作 }); }
3. Rest/Spread attribute:
ES2018 extends Rest/Spread syntax to object destruction:
const myObject = { a: 1, b: 2, c: 3 }; const { a, ...x } = myObject; // a = 1, x = { b: 2, c: 3 } function restParam({ a, ...x }) { // a = 1, x = { b: 2, c: 3 } }
Spread operator is used to create shallow copies or merge objects of objects:
const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 }; // obj2 = { a: 1, b: 2, c: 3 }
4. Regular expression enhancement:
(?<name>...)
to improve readability and maintenance: const reDate = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
(?...<name>...)</name>
, matching the pattern that appeared before. s
(dotAll) flag: .
Match all characters, including line breaks. p{...}
and P{...}
to access Unicode character attributes. ES2018 FAQ:
Promise.finally()
, Rest/Spread attributes, regular expression enhancement, etc. I hope the above information will be helpful to you!
The above is the detailed content of What's New in ES2018. For more information, please follow other related articles on the PHP Chinese website!