webveuje/es6/promise.html
2021-03-23 10:58:10 +08:00

89 lines
2.3 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- <script type="module" src="./b.js"></script> -->
<script>
// 定义一个 promise 对象
// var promise = new Promise(function (resolve, reject) {
// // resolve 成功状态下调用的函数
// // reject 失败状态下调用的函数
// if (成功) {
// resolve()
// } else {
// reject()
// }
// })
// console.log(promise)
// // 使用promise 对象
// promise.then(function (res) {
// console.log(res) //成功返回的值
// }).catch(function (err) {
// console.log(err) //失败返回的值
// })
// function timeout(ms) {
// return new Promise((resolve, reject) => {
// setTimeout(resolve, ms, 'done');
// });
// }
// timeout(100).then((value) => {
// console.log(value);
// });
const getJSON = function (url) {
const promise = new Promise(function (resolve, reject) {
const handler = function () {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
// client.setRequestHeader("Accept", "application/json");
client.send();
});
return promise;
};
getJSON("/posts.json").then(function (json) {
console.log('Contents: ' + json);
}).catch(function(err){
console.log(err)
});
async function s(){
var list =await getJSON("url")
}
</script>
</head>
<body>
</body>
</html>