1 Star 0 Fork 0

Hanley / study-front

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
14th.html 2.25 KB
一键复制 编辑 原始数据 按行查看 历史
hanley 提交于 2018-06-10 20:51 . Promise
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Promise</title>
<script>
//ES6中 Promise对象是一个构造函数,用来生成Promise
//它接收一个函数(function作为参数),这个参数function有两个参数,分别是resolve,reject
//promise是对原始ajax的封装,可以进行串行调用(维护多个异步请求)
//resolve的作用是 promise对象的状态从未完成到成功,成功后异步操作结果作为参数传递
//reject的作用是 promise对象的状态从未完成到失败,失败后异步操作结果作为参数传递
//then()方法分别指定resolve reject 的回到函数
//deferred就是jQuery中promise的实现
//then() done() 实现链式调用 区别是then()传递的方法有返回值,下一个链式调用该方法,done()不会再调用后面的then()
window.onload = function(){
var promise = new Promise(function(resolve,reject){});
promise.then(function(){});//成功
promise.catch(function(){});//失败
}
//jQuery 1.5.0之前版本返回的是XHR对象,1.5.0之后返回的是deferred对象
//封装的原生Promise
const getJSON = function(url,type, data) {
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(type, url);
client.onreadystatechange = handler;
client.responseType = "json";
if(type =='get'){
client.send();
}else {
client.setRequestHeader("Content-Type", "application/json");
client.send(JSON.stringify(data));
}
});
return promise;
};
</script>
</head>
<body>
</body>
</html>
1
https://gitee.com/thanlin/study.git
git@gitee.com:thanlin/study.git
thanlin
study
study-front
master

搜索帮助