4. Promises in ES6
Represents the state of an asynchronous operation, and has three different states
Pending: The initial state of promise
Fulfilled: The state of promise representing a successful operation
Rejected: The state of promise representing a failed operation
Create a promise like
Where myPromiseObject is defined as
Implement the “Fulfill” and “Reject” promise as
5. Promises in ES6
Resolving multiple promises
Resolve using a static method in “Promise” – Promise.all
Promise.all returns a promise (All promise parameters should be in the fulfilled state for Promise.all to be fulfilled)
7. Generators in ES6
Watching a movie on Netflix
Your phone rings
You pause the movie, to attend the phone
You finish the call to resume the movie on Netflix, you don’t restart the movie
8. Generators in ES6
A generator function is recognized by “function * function_name”
10. Iterators in ES6
Currently we can iterate through arrays like [‘Hi’, ‘This’, ‘is’, ‘an’, ‘array’]; using the for, while, or, for…of loops
But how will we iterate through object using the same logic?
Use iterators instead, using the “Symbol.iterator” keyword
“Symbol.iterator” returns an “iterator” object.
An ”iterator” object
Has a method called “next” (What we saw in the generators)
Return an object with keys “value” and “done” (eg: {value: 1, done: false})
13. Set in ES6
Set is a collection of unique values
Values can be primitive types, or object references (as long as they are unique);
Create a set by “new Set()”
Note that since I am trying to add the value “Sharma” twice, the set will ignore the last addition, and will have it only
once without throwing any errors
Iterate over the set using the for…of loop or the forEach loop
14. Maps in ES6
Maps are a store for key / value pairs. Key and value could be a primitives or object references
Create a map using the ”new Map()”
Keys of values in a map can be any thing (String, Integer, or an Object reference)
Get all keys of a map by using the ”keys()” method
Iterate over the map items using the forEach or the for…of loops
15. WeakMap in ES6
WeakMap – a variant of a map that allows objects as keys and removes them once they become inaccessible by
other means.
WeakMap doesn’t support methods keys(), values(), entries(), also, we cannot iterate over them.
WeakMap only has the following functions
weakMap.get(key)
weakMap.set(key)
weakMap.delete(key, value)
weakMap.has(key);
WeakMap v/s Map