-
Notifications
You must be signed in to change notification settings - Fork 4
/
promises.js
63 lines (55 loc) · 1.15 KB
/
promises.js
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
var log = require('./log');
// Promise version
var async1 = function(input) {
return new Promise(function(resolve, reject) {
log('async1, input:', input);
resolve(++input);
});
};
var async2 = function(input) {
return new Promise(function(resolve, reject) {
log('async2, input:', input);
///////////////////////
// Ways to report error
///////////////////////
// reject(Error('error callback from sync2'));
// return reject(Error('error callback from sync2'));
// throw new Error('throw from async2');
///////////////////////
resolve(++input);
});
};
var async3 = function(input) {
return new Promise(function(resolve, reject) {
log('async3, input:', input);
resolve(++input);
});
};
var delay = function(ms) {
return new Promise(function(resolve, reject) {
log('delay, ms:', ms);
setTimeout(
function() {
log('delay: done');
resolve();
},
ms
);
});
};
async1(0)
.then(function(r1) {
return delay(2000)
.then(function() {
return async2(r1);
});
})
.then(function(r3) {
return async3(r3);
})
.then(function(r4) {
log('Result:', r4);
})
.catch(function(e) {
log('Catched!', e);
});