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
0 commit comments