-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromises.js
More file actions
48 lines (39 loc) · 1.58 KB
/
promises.js
File metadata and controls
48 lines (39 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const myPromise = new Promise((resolve, reject) => {
if (Math.random() * 100 < 90) {
console.log('resolving the promise ...');
resolve('Hello, Promises!');
}
reject(new Error('In 10% of the cases, I fail. Miserably.'));
});
// Two functions
const onResolved = (resolvedValue) => console.log(resolvedValue);
const onRejected = (error) => console.log(error);
myPromise.then(onResolved, onRejected);
// Same as above, written concisely
myPromise.then((resolvedValue) => {
console.log(resolvedValue);
}, (error) => {
console.log(error);
});
//.then() accepts two callbacks. The first callback is invoked when the promise is resolved.
//The second callback is executed when the promise is rejected.
// Output (in 90% of the cases)
// resolving the promise ...
// Hello, Promises!
// Hello, Promises!
/*A promise can only succeed(resolved) or fail(reject) once. It cannot succeed or fail twice,
neither can it switch from success to failure or vice versa. If a promise has succeeded or
failed and you later add a success/failure callback (i.e a .then), the correct callback will be called,
even though the event took place earlier.*/
const myProimse = new Promise((resolve, reject) => {
if (Math.random() * 100 < 90) {
reject(new Error('The promise was rejected by using reject function.'));
}
throw new Error('The promise was rejected by throwing an error');
});
myProimse.then(
() => console.log('resolved'),
(error) => console.log(error.message)
);
// Output (in 90% of cases)
// The promise was rejected by using reject function.