js0024

生成器和promise 的结合

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
<!DOCTYPE html>
<html>
<head>
<title>Combining generators and promises</title>
<meta charset="utf-8">
<link rel="stylesheet" href="../assert.css">
<script src="../assert.js"></script>
<script src="getJSON.js"></script>
<script>
"use strict"
async(function*(){
try {
const ninjas = yield getJSON("data/ninjas.json");
const missions = yield getJSON(ninjas[0].missionsUrl);
const missionDescription = yield getJSON(missions[0].detailsUrl);

assert(ninjas !== null && missions !== null
&& missionDescription !== null,
"All ready!");
}
catch(e) {
fail("We weren't able to get mission details");
}
});

function async(generator) {
const iterator = generator();

function handle(iteratorResult) {
if(iteratorResult.done) { return; }

const iteratorValue = iteratorResult.value;

if(iteratorValue instanceof Promise) {
iteratorValue.then(res => handle(iterator.next(res)))
.catch(err => iterator.throw(err))
}
}

try {
handle(iterator.next());
}
catch (e) { iterator.throw(e); }
}
</script>
</head>
<body>Has to be run on a server (e.g MAMP or WAMP)</body>
</html>