Search⌘ K
AI Features

ES2018: Async Iteration and More

Learn about key ES2018 JavaScript updates including async iteration using for-await-of loops, rest and spread syntax for objects, the Promise.finally method, and improved regular expression features such as dotAll flag, named capture groups, lookbehind assertions, and Unicode property escapes. This lesson helps you understand how these modern features enhance asynchronous operations, object handling, and pattern matching in JavaScript.

Rest / Spread for Objects

ES6 (ES2015) allowed us to do this?

Javascript (babel-node)
const veggie = ["tomato","cucumber","beans"];
const meat = ["pork","beef","chicken"];
const menu = [...veggie, "pasta", ...meat];
console.log(menu);
// Array [ "tomato", "cucumber", "beans", "pasta", "pork", "beef", "chicken" ]

Now we can use the rest/spread syntax for objects too, let’s look at how:

Node.js
let myObj = {
a:1,
b:3,
c:5,
d:8,
}
// we use the rest operator to grab everything else left in the object.
let { a, b, ...z } = myObj;
console.log(a); // 1
console.log(b); // 3
console.log(z); // {c: 5, d: 8}
// using the spread syntax we cloned our Object
let clone = { ...myObj };
console.log(clone);
// {a: 1, b: 3, c: 5, d: 8}
myObj.e = 15;
console.log(clone)
// {a: 1, b: 3, c: 5, d: 8}
console.log(myObj)
// {a: 1, b: 3, c: 5, d: 8, e: 15}

With the spread operator we can easily create a clone of our Object so that when we modify the original Object, the clone does not get modified.

 

Asynchronous iteration

With asynchronous iteration we can iterate asynchronously over our data.

From the documentation:

An async iterator is much like an iterator, except that its next() method returns a promise for a { value, done } pair.

To do so, we will use a for-await-of loop which works by converting our iterables to a promise, unless they already are one.

Node.js
const iterables = [1,2,3];
async function test() {
for await (const value of iterables) {
console.log(value);
}
}
test();
// 1
// 2
// 3

During execution, an async iterator is created from the data source using the [Symbol.asyncIterator]() method. Each time we access the next value in the sequence, we implicitly await the promise returned from the iterator method.

 

Promise.prototype.finally()

...