Skip to content

Commit f5bb4f1

Browse files
author
Vitalii Telychko
committed
fn
1 parent 0c49e61 commit f5bb4f1

19 files changed

+518
-64
lines changed

ES6/Arrow_functions/overview.js

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// function Prefixer(prefix) {
2+
// this.prefix = prefix;
3+
// }
4+
// Prefixer.prototype.prefixArray = function (arr) { // (A)
5+
// 'use strict';
6+
// return arr.map(function (x) { // (B)
7+
// // Doesn’t work:
8+
// return this.prefix + x; // (C)
9+
// });
10+
// };
11+
12+
13+
// In line C, we’d like to access this.prefix,
14+
// but can’t, because the this of the function from line B shadows the this of the method from line A.
15+
16+
// SOLUTIONS
17+
// 1. that = this
18+
19+
// function Prefixer(prefix) {
20+
// this.prefix = prefix;
21+
// }
22+
// Prefixer.prototype.prefixArray = function (arr) {
23+
// var that = this; // (A)
24+
// return arr.map(function (x) {
25+
// return that.prefix + x;
26+
// });
27+
// };
28+
29+
// 2. specifying a value for this
30+
// function Prefixer(prefix) {
31+
// this.prefix = prefix;
32+
// }
33+
// Prefixer.prototype.prefixArray = function (arr) {
34+
// return arr.map(function (x) {
35+
// return this.prefix + x;
36+
// }, this); // (A)
37+
// };
38+
39+
// 3. bind(this)
40+
41+
// function Prefixer(prefix) {
42+
// this.prefix = prefix;
43+
// }
44+
// Prefixer.prototype.prefixArray = function (arr) {
45+
// return arr.map(function (x) {
46+
// return this.prefix + x;
47+
// }.bind(this)); // (A)
48+
// };
49+
50+
// 4. ES6
51+
// function Prefixer(prefix) {
52+
// this.prefix = prefix;
53+
// }
54+
// Prefixer.prototype.prefixArray = function (arr) {
55+
// return arr.map((x) => this.prefix + x);
56+
// };
57+
58+
// Immediately Invoked Arrow Function (IIAF)
59+
// (() => {
60+
// return 123
61+
// })();
62+
63+
// typeof (() => {})
64+
// 'function'
65+
// () => {} instanceof Function
66+
// true
67+
//
68+
// typeof function () {}
69+
// 'function'
70+
// function () {} instanceof Function
71+
// true
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// console.log(typeof () => {}); // SyntaxError
2+
// console.log(typeof (() => {})); // OK
3+
4+
// const func1 = (x, y) // SyntaxError
5+
// => {
6+
// return x + y;
7+
// };
8+
// const func2 = (x, y) => // OK
9+
// {
10+
// return x + y;
11+
// };
12+
13+
// const f1 = x => ({ bar: 123 });
14+
// f1()
15+
// { bar: 123 }

ES6/Promises/3_ways_understanding.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// ES6
2+
3+
// function asyncFunc() {
4+
// return new Promise((resolve, reject) => { // (A)
5+
// setTimeout(() => resolve('DONE'), 100); // (B)
6+
// });
7+
// }
8+
//
9+
//
10+
// asyncFunc()
11+
// .then(x => console.log('Result: ' + x));
12+
13+
// ES8
14+
15+
// async function main() {
16+
// const x = await asyncFunc();
17+
// console.log('Result: ' + x);
18+
// }
19+
//
20+
// main();
21+
22+
// SO
23+
// Conceptually, invoking asyncFunc() is a blocking function call.
24+
// A Promise is both a container for a value and an event emitter.
25+
26+
// 1. Calling a Promise-based function is blocking
27+
// 2. A Promise is a container for an asynchronously delivered value
28+
// 3. A Promise is an event emitter
29+
30+
// The same
31+
// promise.then(
32+
// null,
33+
// error => { /* rejection */ });
34+
//
35+
// promise.catch(
36+
// error => { /* rejection */ });

ES6/Promises/chaining_promises.js

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// 1. Mistake: losing the tail of a Promise chain
2+
3+
// // Don’t do this
4+
// function foo() {
5+
// const promise = asyncFunc();
6+
// promise.then(result => {
7+
// // ···
8+
// });
9+
//
10+
// return promise;
11+
// }
12+
//
13+
// function foo() {
14+
// const promise = asyncFunc();
15+
// return promise.then(result => {
16+
// // ···
17+
// });
18+
// }
19+
//
20+
// function foo() {
21+
// return asyncFunc()
22+
// .then(result => {
23+
// // ···
24+
// });
25+
// }
26+
27+
// 2. Mistake: nesting Promises
28+
29+
// Don’t do this
30+
// asyncFunc1()
31+
// .then(result1 => {
32+
// asyncFunc2()
33+
// .then(result2 => {
34+
// // ···
35+
// });
36+
// });
37+
//
38+
// asyncFunc1()
39+
// .then(result1 => {
40+
// return asyncFunc2();
41+
// })
42+
// .then(result2 => {
43+
// // ···
44+
// });
45+
46+
// 3. Mistake: creating Promises instead of chaining
47+
// 4. Mistake: using then() for error handling
48+
49+
// In principle, catch(cb) is an abbreviation for then(null, cb).
50+
// But using both parameters of then() at the same time can cause problems.

ES6/Promises/error_handling.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Operational errors happen when a correct program encounters an exceptional situation that requires deviating
2+
// from the “normal” algorithm. For example, a storage device may run out of memory while the program is writing data to it.
3+
// This kind of error is expected.
4+
// Programmer errors happen when code does something wrong.
5+
// For example, a function may require a parameter to be a string, but receives a number.
6+
// This kind of error is unexpected.
7+
8+
// Promise.race()
9+
10+
// var p1 = new Promise(function(resolve, reject) {
11+
// setTimeout(resolve, 1500, 'one');
12+
// });
13+
//
14+
// var p2 = new Promise(function(resolve, reject) {
15+
// setTimeout(resolve, 1100, 'two');
16+
// });
17+
//
18+
// Promise.race([p1, p2]).then(function(value) {
19+
// console.log(value); // "two"
20+
// // Both resolve, but p2 is faster
21+
// });
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// 1. Promise.resolve()
2+
3+
// Promise.resolve('abc')
4+
// .then(x => console.log(x)); // 'abc'
5+
6+
// const fulfilledThenable = {
7+
// then(reaction) {
8+
// reaction('hello');
9+
// }
10+
// };
11+
// const promise = Promise.resolve(fulfilledThenable);
12+
// console.log(promise instanceof Promise); // true
13+
// promise.then(x => console.log(x)); // hello
14+
15+
// That means that you can use Promise.resolve() to convert any value (Promise, thenable or other) to a Promise.
16+
// In fact, it is used by Promise.all() and Promise.race() to convert Arrays of arbitrary values to Arrays of Promises.
17+
18+
19+
// 2. Promise.reject()
20+
21+
// const myError = new Error('Problem!');
22+
// Promise.reject(myError)
23+
// .catch(err => console.log(err === myError)); // true

ES6/Promises/overview.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// 1. Via callback
2+
3+
// asyncFunction(arg1, arg2,
4+
// result => {
5+
// console.log(result);
6+
// });
7+
8+
// 2. Via Promise
9+
10+
// asyncFunction(arg1, arg2) // return an object
11+
// .then(result => {
12+
// console.log(result);
13+
// });

ES6/Promises/promise_anti_patterns.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Nested Promises
2+
3+
// BAD
4+
// loadSomething().then(function(something) {
5+
// loadAnotherthing().then(function(another) {
6+
// DoSomethingOnThem(something, another);
7+
// });
8+
// });
9+
10+
// GOOD
11+
// q.all([loadSomething(), loadAnotherThing()])
12+
// .spread(function(something, another) {
13+
// DoSomethingOnThem(something, another);
14+
// });
15+
16+
// The Broken Chain
17+
18+
// BAD
19+
// function anAsyncCall() {
20+
// var promise = doSomethingAsync();
21+
// promise.then(function() {
22+
// somethingComplicated();
23+
// });
24+
//
25+
// return promise;
26+
// }
27+
28+
// GOOD
29+
// function anAsyncCall() {
30+
// var promise = doSomethingAsync();
31+
// return promise.then(function() {
32+
// somethingComplicated()
33+
// });
34+
// }

ES6/Promises/simple_examples.js

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
// 1.
2+
// import {readFile} from 'fs';
3+
//
4+
// function readFilePromisified(filename) {
5+
// return new Promise(
6+
// function (resolve, reject) {
7+
// readFile(filename, { encoding: 'utf8' },
8+
// (error, data) => {
9+
// if (error) {
10+
// reject(error);
11+
// } else {
12+
// resolve(data);
13+
// }
14+
// });
15+
// });
16+
// }
17+
//
18+
// readFilePromisified(process.argv[2])
19+
// .then(text => {
20+
// console.log(text);
21+
// })
22+
// .catch(error => {
23+
// console.log(error);
24+
// });
25+
26+
// 2.
27+
28+
// function httpGet(url) {
29+
// return new Promise(
30+
// function (resolve, reject) {
31+
// const request = new XMLHttpRequest();
32+
// request.onload = function () {
33+
// if (this.status === 200) {
34+
// // Success
35+
// resolve(this.response);
36+
// } else {
37+
// // Something went wrong (404 etc.)
38+
// reject(new Error(this.statusText));
39+
// }
40+
// };
41+
// request.onerror = function () {
42+
// reject(new Error(
43+
// 'XMLHttpRequest Error: '+this.statusText));
44+
// };
45+
// request.open('GET', url);
46+
// request.send();
47+
// });
48+
// }
49+
//
50+
// httpGet('http://example.com/file.txt')
51+
// .then(
52+
// function (value) {
53+
// console.log('Contents: ' + value);
54+
// },
55+
// function (reason) {
56+
// console.error('Something went wrong', reason);
57+
// });
58+
59+
60+
// 3.
61+
62+
// function delay(ms) {
63+
// return new Promise(function (resolve, reject) {
64+
// setTimeout(resolve, ms); // (A)
65+
// });
66+
// }
67+
//
68+
// // Using delay():
69+
// delay(3000).then(function () { // (B)
70+
// console.log('5 seconds have passed!')
71+
// }, function () {
72+
// console.log('Error');
73+
// });
74+
75+
// 4.
76+
// function timeout(ms, promise) {
77+
// return new Promise(function (resolve, reject) {
78+
// promise.then(resolve);
79+
// setTimeout(function () {
80+
// reject(new Error('Timeout after '+ms+' ms')); // (A)
81+
// }, ms);
82+
// });
83+
// }
84+
//
85+
// timeout(5000, httpGet('http://example.com/file.txt'))
86+
// .then(function (value) {
87+
// console.log('Contents: ' + value);
88+
// })
89+
// .catch(function (reason) {
90+
// console.error('Error or timeout', reason);
91+
// });
92+
93+
// Note that the rejection after the timeout (in line A) does not cancel the request,
94+
// but it does prevent the Promise being fulfilled with its result
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// https://blog.domenic.me/the-revealing-constructor-pattern/
2+
3+
var p = new Promise(function (resolve, reject) { // “executor function”
4+
// Use `resolve` to resolve `p`.
5+
// Use `reject` to reject `p`.
6+
});
7+
8+
// I call this the revealing constructor pattern because the Promise constructor is revealing its internal capabilities,
9+
// but only to the code that constructs the promise in question.
10+
// The ability to resolve or reject the promise is only revealed to the constructing code,
11+
// and is crucially not revealed to anyone using the promise.

index.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,6 @@
1010

1111
<div id="content"></div>
1212

13-
<script src="ES6/Promises/overview.js"></script>
13+
<script src="programming_paradigms/functional_programming/reduce.js"></script>
1414
</body>
1515
</html>

0 commit comments

Comments
 (0)