forked from LightSpeedWorks/async-await
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aa-readme-ex02-par.js
56 lines (42 loc) · 1.1 KB
/
aa-readme-ex02-par.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
try {
var aa = require('../aa');
} catch (e) {
var aa = require('aa');
}
aa(main);
function *main() {
console.log('[11, 12, 13]:', yield [
asyncPromise(100, 11),
asyncThunk(100, 12),
asyncGenerator(100, 13)
]);
console.log('{x:11, y:12, z:13}:', yield {
x: asyncPromise(100, 11),
y: asyncThunk(100, 12),
z: asyncGenerator(100, 13)
});
yield [sub(20), sub(30)];
}
function *sub(base) {
console.log('%s: %s', base + 1, yield asyncPromise(100, base + 1));
console.log('%s: %s', base + 2, yield asyncThunk(100, base + 2));
console.log('%s: %s', base + 3, yield asyncGenerator(100, base + 3));
}
// asyncPromise(msec, arg) : promise
function asyncPromise(msec, arg) {
return new Promise(function (resolve, reject) {
setTimeout(resolve, msec, arg);
});
}
// asyncThunk(msec, arg) : thunk
function asyncThunk(msec, arg) {
return function (callback) {
setTimeout(callback, msec, null, arg);
};
}
// asyncGenerator(msec, arg) : generator
function *asyncGenerator(msec, arg) {
var chan = aa.Channel();
setTimeout(chan, msec, arg);
return yield chan;
}