-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise.js
More file actions
85 lines (65 loc) · 1.89 KB
/
promise.js
File metadata and controls
85 lines (65 loc) · 1.89 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const doAsyncTask = () => {
const promise = new Promise((resolve, reject) => {
console.log('Async task completed');
if(false){
resolve('Async data');
} else {
reject('Something went wrong!');
}
});
return promise;
}
// Using then and catch to capture success(resolve) & failure(reject)
doAsyncTask().then((data) => {
console.log('Got data: ', data);
}).catch((err) => {
console.log('Error: ', err);
});
/* using second param to then to capture reject */
doAsyncTask().then((data) => {
console.log('Got data: ', data);
}, (err) => {
console.log('Without using catch ', err);
})
console.log('----------------------------------------');
// promise way
const doAsyncTask1 = () => {
const promise = new Promise((resolve, reject) => {
console.log('Async task completed');
setTimeout(() => {
resolve('Found data!');
}, 5000);
});
return promise;
}
console.log(doAsyncTask1());
doAsyncTask1().then((data) => {
console.log('Got data: ', data);
}).catch((err) => {
console.log('Error: ', err);
});
console.log('----------------------------------------');
// callback way
const doAsyncTask2 = (cb) => {
setTimeout(()=> {
cb();
}, 5000);
}
doAsyncTask2(() => {console.log('Completed')});
console.log('----------------------------------------');
/*
Immediately resolve or rejected Promise
*/
let promise = Promise.resolve('done!');
// promise = Promise.reject('Errrr!');
promise.then((val) => {console.log(val)});
console.log('----------------------------------------');
/*
Promise is 100% asynchronous by default but callback are not asunchronous by default.
*/
function doAsyncTask4() {
return Promise.resolve();
}
doAsyncTask4().then(() => { console.log(message)});
let message = 'blah blah blah';
console.log('----------------------------------------');