-
Notifications
You must be signed in to change notification settings - Fork 0
/
Promise.html
60 lines (51 loc) · 2.31 KB
/
Promise.html
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
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
var taskSet = [
{nr:1, name: "one", url: "https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=16ef420c60f8899b3617e773b56508ee&photoset_id=72157644400632823&format=json&nojsoncallback=1&api_sig=4607cf37743a2797c5da1735582c9ac6"}
,{nr:2, name: "zwo", url: "https://api.flickr.com/services/rest/?method=flickr.test.echo&api_key=1e4a63d700064d6eba2bca1aeefdd842&format=json&&nojsoncallback=1"}
,{nr:3, name: "zwo", url: "https://api.flickr.com/services/rest/?method=flickr.test.echo&api_key=16ef420c60f8899b3617e773b56508ee&format=json&&nojsoncallback=1"}
];
window.onload = function () {
var tasks = [];
taskSet.forEach(function (taskDef) {
console.info("creating task for", taskDef.name);
var p = new Promise(function(resolve, reject) {
getXhr(taskDef.url, function(data){
console.info(data);
resolve({task: taskDef, data: data});
}).send();
});
tasks.push(p);
})
Promise.all(tasks).then(function(value){
console.log("Promise.all", value);
var result = [];
var output = document.createElement("ul");
value.forEach(function(val){
result.push( val.data.type === 'load' ? val.data.target.response : val.data);
var li = document.createElement("li");
li.innerHTML = "Task: " + val.task.name + ", Result: " + result[result.length-1];
output.appendChild(li);
})
console.info("ALL DONE with result", result);
document.documentElement.lastElementChild.appendChild(output);
});
};
var getXhr = function(url, success, error) {
console.info("build xhr");
var xhr = new XMLHttpRequest();
xhr.onload = success;
xhr.onerror = error;
xhr.open("GET", url);
//xhr.setRequestHeader("Content-Type", "application/jsonp");
return xhr;
}
</script>
</head>
<body>
</body>
</html>