Promise入门

Promise 是什么

Promise 是抽象异步处理对象以及对其进行各种操作的组件。
Promise 提供了一种可以使用对象和方法来代替回调函数的异步事件处理方法。

Promise Chain

DEMO

HTML:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://www.promisejs.org/polyfills/promise-7.0.4.min.js"></script>
<script src="Promise.js"></script>
</head>
<body>

</body>
</html>

JavaScript:

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
/**
* Created by RichardLu on 3/30/16.
*/
function getURL(URL) {
return new Promise( function (resolve, reject){
var req = new XMLHttpRequest();
req.open('GET', URL, true);
req.onload = function () {
if (req.status === 200) {
resolve(req.responseText);
} else {
reject(new Error(req.statusText));
}
};
req.onerror = function () {
reject(new Error(req.statusText));
};
req.send();
});
}


var request = {
comment: function getComment() {
return getURL('http://azu.github.io/promises-book/json/comment.json').then(JSON.parse);
},
people: function getPeople() {
return getURL('http://azu.github.io/promises-book/json/people.json').then(JSON.parse);
}
}

function main() {
function recordValue(results, value) {
results.push(value);
return results;
}

var pushValue = recordValue.bind(null, []);
return request.comment().then(pushValue).then(request.people).then(pushValue);
}


main().then(function (value) {
console.log(value);
}).catch( function(error){
console.log(error);
});