-
Notifications
You must be signed in to change notification settings - Fork 0
ES2015
ES2015, or ES6 as it was previously known, was JavaScript's biggest advance. I'll list the new features in order of their importance (to me!).
#Promises
JavaScript is used is connect Internet resources. Waiting for resources such as remote databases to respond with data is a constant issue. Synchronous code froze websites while waiting for data. Asynchronous coding is the norm now, with the parts of the code running while other parts wait for data.
In ES5 and earlier, asynchronous coding used callbacks. Callbacks are double functions, in which the second function is an argument to the first function. The first function executes and then waits for the data to return, or a user to click a button, etc., and then the second function executes. Here is an example of a callback function:
myFirstFunction(function(error, data) {
if (error) {
console.log(error);
} else {
// render docs
};
});
What if you have five or ten things to do after the data returns or the user clicks the button? You can nest callbacks:
myFirstFunction(function(error, data) {
if (error) {
console.log(error);
} else {
// render docs (function(error, data) {
if (error) {
console.log(error);
} else {
// render docs (function(error, data) {
// and so on...
};
};
});
This is called callback hell or the pyramid of death.
Promises fix this problem. A promise is a proxy for a value which may be available now, in the future, or never.
Promises always have two handlers resolve
and reject
.
Promises have three states: pending, fulfilled, and rejected.
Promise prototypes have two methods that are almost always used:
-
.then(onFulfilled, on Rejected)
takes two arguments, typicallydata
anderror
. -
.catch(onRejected)
takes one argument, typicallyerror
.
Promises have four other methods which are less commonly used:
-
all
is used for aggregating the results of multiple promises into an array of values. -
race
is also used with multiple promises, but returns when one of the promises fulfills. -
reject
-- not sure how this differs fromcatch
. -
resolve
-- not sure how this differs fromthen
.
The basic syntax of promises is:
function myFunction() {
// ...
};
myFunction.then(
// ...
)
.catch(
console.log(error);
);
# let
and const
_Hoisting_ means that JavaScript allows your code to use a variable before it's declared. This can be a problem if you use the same name for different variables. Hoisting also can give you misleading error messages. Using let
instead of var
eliminates hoisting and is generally considered to be good coding.
let
should always be used in for in
loops.
is used for constants, which are also not hoisted.