ES2018: Async Iteration and More
This lesson covers the new features introduced in ES2018
Rest / Spread for Objects
ES6 (ES2015) allowed us to do this?
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:
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); // 1console.log(b); // 3console.log(z); // {c: 5, d: 8}// using the spread syntax we cloned our Objectlet 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.
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.
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.