ES6: Exploring Array Methods and Iterators, Promises, and Async/Await
1. Array Methods and Iterators
ES6 introduced new and powerful array methods that make data manipulation easier and
more expressive. Iterators allow arrays (and other collections) to be traversed in a
standardized way.
Common methods include map(), filter(), reduce(), find(), and forEach().
Example 1: Using map(), filter(), and reduce()
const numbers = [1, 2, 3, 4, 5];
const doubled = [Link](n => n * 2);
const even = [Link](n => n % 2 === 0);
const sum = [Link]((acc, n) => acc + n, 0);
[Link](sum); // Output: 20
2. Promises
A Promise represents the eventual completion (or failure) of an asynchronous operation
and its resulting value.
Example 2: Creating and Using a Promise
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) resolve('Data fetched successfully!');
else reject('Error fetching data');
}, 1000);
});
fetchData
.then(response => [Link](response))
.catch(error => [Link](error));
3. Async/Await
Async/Await is a modern syntax built on top of Promises that allows you to write
asynchronous code in a synchronous manner, making it more readable and maintainable.
Example 3: Using Async/Await
async function fetchUserData() {
try {
const response = await new Promise(resolve =>
setTimeout(() => resolve('User data loaded!'), 1000)
);
[Link](response);
} catch (error) {
[Link](error);
}
}
fetchUserData();
In ES6 (ECMAScript 2015), the primary feature introduced for handling asynchronous
operations more effectively than traditional callbacks was Promises.
The async/await syntax, while built on Promises, was actually introduced in a later version
of the standard (ES2017/ES8).
Promises (ES6)
A Promise is an object representing the eventual completion or failure of an asynchronous
operation and its resulting value. It provides a cleaner, more structured alternative to the
"callback hell" that often resulted from deeply nested callback functions.
Key aspects of Promises:
States: A Promise exists in one of three states:
o Pending: Initial state; the operation has not yet completed.
o Fulfilled (Resolved): The operation completed successfully, and a value is
available.
o Rejected: The operation failed, and a reason (error) is available.
Chaining: Promises allow for chaining multiple asynchronous operations using
the .then() method, which returns a new Promise. This avoids excessive nesting and
makes the code more readable.
Error Handling: The .catch() method provides a centralized way to handle errors
that might occur anywhere in a promise chain, which is much more robust than
error handling with callbacks.
Utility Methods: ES6 also introduced utility methods like [Link]() (waits for
all promises in an array to resolve) and [Link]() (returns the result of the
first promise to resolve or reject).
Example using Promises:
javascript
const fetchData = new Promise((resolve, reject) => {
// Simulate an asynchronous operation (e.g., network request)
setTimeout(() => {
const data = { name: "John", age: 30 };
resolve(data); // Operation succeeded
}, 1000);
});
fetchData
.then(data => {
[Link](data); // Output: { name: 'John', age: 30 }
return [Link]; // Return a value for the next .then()
})
.then(name => {
[Link](`User name: ${name}`); // Output: User name: John
})
.catch(error => {
[Link]('Error:', error); // Handle any errors in the chain
});
[Link]("Data is being fetched..."); // This runs immediately (non-blocking)
Use code with caution.
Generators (ES6)
ES6 also introduced generator functions (function*) and the yield keyword, which allow a
function's execution to be paused and resumed. This feature, when combined with libraries
(like co), provided a way to write asynchronous code in a more synchronous style, paving
the way for the async/await syntax in later JavaScript versions.
async/await (ES2017)
While often associated with ES6 in general discussion, the async and await keywords were
officially added in ES2017 (ES8). They are a syntactic sugar built on top of Promises,
providing the cleanest and most readable way to handle asynchronous code, making it look
almost synchronous.