├── es6 ├── promise │ ├── data.json │ └── promise.js ├── main.js ├── for-of.js ├── Person.js ├── set&map.js ├── iterator.js ├── generator.js └── promise.js ├── Note ├── let.jpg ├── map.jpg ├── set.jpg ├── Array.jpg ├── const.jpg ├── jiegou.jpg ├── number.jpg ├── object.jpg ├── function.jpg ├── promise.jpg └── note.md ├── webpack.config.js ├── index.html ├── package.json └── README.md /es6/promise/data.json: -------------------------------------------------------------------------------- 1 | { 2 | "value":"hello" 3 | } -------------------------------------------------------------------------------- /Note/let.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimplyWenjing/ES6/HEAD/Note/let.jpg -------------------------------------------------------------------------------- /Note/map.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimplyWenjing/ES6/HEAD/Note/map.jpg -------------------------------------------------------------------------------- /Note/set.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimplyWenjing/ES6/HEAD/Note/set.jpg -------------------------------------------------------------------------------- /Note/Array.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimplyWenjing/ES6/HEAD/Note/Array.jpg -------------------------------------------------------------------------------- /Note/const.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimplyWenjing/ES6/HEAD/Note/const.jpg -------------------------------------------------------------------------------- /Note/jiegou.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimplyWenjing/ES6/HEAD/Note/jiegou.jpg -------------------------------------------------------------------------------- /Note/number.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimplyWenjing/ES6/HEAD/Note/number.jpg -------------------------------------------------------------------------------- /Note/object.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimplyWenjing/ES6/HEAD/Note/object.jpg -------------------------------------------------------------------------------- /Note/function.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimplyWenjing/ES6/HEAD/Note/function.jpg -------------------------------------------------------------------------------- /Note/promise.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimplyWenjing/ES6/HEAD/Note/promise.jpg -------------------------------------------------------------------------------- /es6/main.js: -------------------------------------------------------------------------------- 1 | import Person from './Person.js'; 2 | 3 | let p = new Person ('张三',20); 4 | document.write(p.say()); -------------------------------------------------------------------------------- /es6/for-of.js: -------------------------------------------------------------------------------- 1 | //测试for-of循环 2 | var map = new Map(); 3 | map.set ('name','vicky'); 4 | map.set('age','24'); 5 | 6 | for(let [key,value] of map) { 7 | console.log(key + ":" + value); 8 | } -------------------------------------------------------------------------------- /es6/Person.js: -------------------------------------------------------------------------------- 1 | class Person{ 2 | constructor(name,age){ 3 | this.name = name; 4 | this.age = age; 5 | } 6 | 7 | say(){ 8 | return '我是' + ${this.name}',我今年' + ${this.age} + '岁了。'; 9 | } 10 | } 11 | 12 | export default Person; -------------------------------------------------------------------------------- /es6/set&map.js: -------------------------------------------------------------------------------- 1 | var s = new Set(); 2 | [2,3,4,5,5,2,2].map(x => s.add(x)); 3 | for(var i of s ){ 4 | console.log(i);// 2,3,4,5 5 | } 6 | //去除数组中重复元素 7 | function dedupe (array) { 8 | return Array.from(new Set(array)); 9 | } 10 | var array = new Array(1,2,3,3,4,2,1); 11 | console.log(dedupe(array));//[1,2,3,4] -------------------------------------------------------------------------------- /es6/iterator.js: -------------------------------------------------------------------------------- 1 | function makeIterator (array) { 2 | var nextIndex = 0; 3 | return { 4 | next: function () { 5 | return nextIndex < array.length ? {value:array[nextIndex++],done:false}:{value:undefined,done:true}; 6 | } 7 | } 8 | } 9 | 10 | var array = [1,2,3,'a','b']; 11 | for( var a in array) { 12 | console.log(a); 13 | } 14 | for( var a of array) { 15 | console.log(a); 16 | } -------------------------------------------------------------------------------- /es6/generator.js: -------------------------------------------------------------------------------- 1 | function* helloWorldGenerator () { 2 | yield 'hello'; 3 | yield 'world'; 4 | return 'ending'; 5 | } 6 | 7 | var hw = helloWorldGenerator(); 8 | hw.next(); 9 | hw.next(); 10 | hw.next(); 11 | 12 | function* foo() { 13 | yield 1; 14 | yield 2; 15 | yield 3; 16 | yield 4; 17 | yield 5; 18 | return 6; 19 | } 20 | 21 | for( let v of foo()) { 22 | console.log(v); 23 | } -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | module.exports = { 3 | entry: "./Code/set&map.js", 4 | output: { 5 | path: __dirname, 6 | filename: "bundle.js" 7 | }, 8 | module: { 9 | loaders: [ 10 | { 11 | test: path.join(__dirname, 'es6'), 12 | loader: 'babel-loader', 13 | query: { 14 | presets: ['es2015'] 15 | } 16 | } 17 | ] 18 | } 19 | } -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 测试页面 6 | 18 | 19 | 20 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "es6", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "guwenjing", 10 | "license": "ISC", 11 | "dependencies": { 12 | "babel-core": "^6.9.1", 13 | "babel-loader": "^6.2.4", 14 | "babel-polyfill": "^6.0.16", 15 | "babel-preset-es2015": "^6.9.0", 16 | "babel-preset-react": "^6.5.0", 17 | "install": "^0.8.1", 18 | "react": "^15.1.0", 19 | "react-dom": "^15.1.0", 20 | "webpack": "^1.13.1" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /es6/promise.js: -------------------------------------------------------------------------------- 1 | function helloWorld (ready) { 2 | return new Promise(function (resolve, reject) { 3 | if (ready) { 4 | resolve("Hello World!"); 5 | } else { 6 | reject("Good bye!"); 7 | } 8 | }); 9 | } 10 | 11 | // helloWorld(false).then(function (message) { 12 | // alert(message); 13 | // }, function (error) { 14 | // alert(error); 15 | // }); 16 | 17 | 18 | function printHello (ready) { 19 | return new Promise(function (resolve, reject) { 20 | if (ready) { 21 | resolve("Hello"); 22 | } else { 23 | reject("Good bye!"); 24 | } 25 | }); 26 | } 27 | 28 | function printWorld () { 29 | alert("World"); 30 | } 31 | 32 | function printExclamation () { 33 | alert("!"); 34 | } 35 | 36 | printHello(true) 37 | .then(function(message){ 38 | alert(message); 39 | }) 40 | .then(printWorld) 41 | .then(printExclamation); -------------------------------------------------------------------------------- /es6/promise/promise.js: -------------------------------------------------------------------------------- 1 | function timeout (ms) { 2 | return new Promise ((resolve,reject) => { 3 | setTimeout(resolve,ms,'done'); 4 | }); 5 | } 6 | 7 | timeout(100).then ((value) => { 8 | console.log(value); 9 | }); 10 | 11 | //用Promise实现Ajax 12 | 13 | var getJSON = function (url) { 14 | var promise = new Promise (function (resolve,reject){ 15 | var xhr = new XMLHttpRequest(); 16 | xhr.onreadystatechange = handler; 17 | xhr.open("GET",url); 18 | // xhr.responseType = 'json'; 19 | // xhr.setRequestHeader("Accept","application/json"); 20 | xhr.send(); 21 | function handler () { 22 | if (this.readyState == 4) { 23 | if (this.status >= 200 && this.status < 300 || this.status == 304) { 24 | resolve(this.responseText); 25 | } else { 26 | reject(new Error (this.statusText)); 27 | } 28 | } 29 | };; 30 | }); 31 | return promise; 32 | }; 33 | 34 | getJSON("../../../es6/es6/promise/data.json").then(function (json) { 35 | console.log("sucess:" + json); 36 | },function (error) { 37 | console.log("error:" + error); 38 | }); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ES6 2 | * ES6的学习笔记and代码练习 3 | * 基于webpack打包 4 | 5 | ## 很久没有看github了,没有想到很多人在看这个es6的学习分享,里面可能有很多错误,但是我现在不做前端了,很多前端知识都忘记了,如果里面有错误,恳请大家帮忙改正!祝大家早日成为优秀的前端工程师! 6 | 7 | ## let 8 | 9 | ![let](https://github.com/SimplyWenjing/ES6/blob/master/Note/let.jpg) 10 | 11 | ## const 12 | ![const](https://github.com/SimplyWenjing/ES6/blob/master/Note/const.jpg) 13 | 14 | ## 数值的扩展 15 | ![数值的扩展](https://github.com/SimplyWenjing/ES6/blob/master/Note/number.jpg) 16 | 17 | ## 数组的扩展 18 | ![Array](https://github.com/SimplyWenjing/ES6/blob/master/Note/Array.jpg) 19 | 20 | ## 解构赋值 21 | ![解构](https://github.com/SimplyWenjing/ES6/blob/master/Note/jiegou.jpg) 22 | 23 | ##函数扩展 24 | ![function](https://github.com/SimplyWenjing/ES6/blob/master/Note/function.jpg) 25 | 26 | ##对象的扩展 27 | ![object](https://github.com/SimplyWenjing/ES6/blob/master/Note/object.jpg) 28 | 29 | ## Set and Map 30 | ![Set and Map](https://github.com/SimplyWenjing/ES6/blob/master/Note/set.jpg) 31 | ![Set and Map](https://github.com/SimplyWenjing/ES6/blob/master/Note/map.jpg) 32 | 33 | ## Promise 34 | ![Promise](https://github.com/SimplyWenjing/ES6/blob/master/Note/promise.jpg) 35 | 36 | -------------------------------------------------------------------------------- /Note/note.md: -------------------------------------------------------------------------------- 1 | #0、raceur编译器 2 | Google公司的Traceur(http://github.com/google/traceur-compiler)编译器,可以将ES6代码编译为ES5代码。 3 | 使用方法:直接插入网页 4 | 首先,必须在网页头部加载Traceur库文件 5 | ``` 6 | 7 | 8 | 11 | 14 | ``` 15 | type属性的值是module,这是Traceur用来辨识ES6代码的标识,编译器会自动将所有标记了type=module的代码编译为ES5代码,然后交给浏览器执行 16 | #1、let命令 17 | ES6新增了let命令,用于声明变量,用let声明的变量,只在let命令所在的代码块内有效。 18 | let其实是为JavaScript新增了块级作用域。 19 | #2、const命令 20 | const用来声明常量,一旦声明,其值就不能改变。 21 | const与let的作用域相同,只在声明所在的块级作用域内有效。 22 | const声明的常量不可重复声明 23 | #3、数组的解构 24 | ES6允许按照一定模式,从数组和对象中提取值,对变量进行复制,这被称为解构 25 | 例如 var [a,b,c] = [1,2,3]//本质上属于模式匹配,只要两边的模式相同,左边的变量就会被赋予相应的值。 26 | 注意:解构只能用于数组或者对象。其他原始类型的值都可以转化为相应的对象,但是undefined和null不能转化为对象,所以不能够解构。 27 | 对象的解构: 28 | 数组的元素是按照次序排列的,变量的取值由它的位置决定,而对象的属性没有次序,变量必须与属性同名,才能取到正确的值 29 | 解构的用途: 30 | (1)交换变量的值 31 | (2)从函数返回多个值 32 | ``` 33 | function example (){ 34 | return [1,2,3]; 35 | } 36 | var [a,b,c] = example(); 37 | ``` 38 | (3) 函数参数的定义 39 | ``` 40 | funciton f({x,y,z}){ 41 | //... 42 | } 43 | f({x:1,y:2,z:3}) 44 | ``` 45 | (4) 函数参数的默认值 46 | ``` 47 | jQuery.ajax= function (url,{ 48 | async = true, 49 | beforeSend = function () {}, 50 | cache = true, 51 | complete = function () {}, 52 | crossDomain = false, 53 | global = true. 54 | }) { 55 | //... 56 | } 57 | ``` 58 | #4、for-of 循环 59 | 任何部署了Iterator接口的对象,都可以使用for-of循环遍历。 60 | 我们如何遍历数组中的元素: 61 | (1) for循环 62 | ``` 63 | for (var index = 0; index < myArray.length; index++) { 64 | console.log(myArray[index]); 65 | } 66 | ``` 67 | (2) forEach方法遍历数组 68 | ``` 69 | myArray.forEach(function (value) { 70 | console.log(value); 71 | }); 72 | ``` 73 | (3) for-in循环 74 | ``` 75 | for (var index in myArray) { // 千万别这样做!! 76 | console.log(myArray[index]); 77 | } 78 | ``` 79 | 这绝对是一个糟糕的选择,为什么呢? 80 | 1)在这段代码中,赋给index的值不是实际的数字,而是字符串“0”、“1”、“2”,此时很可能在无意之间进行字符串算数计算,例如:“2” + 1 == “21”,这给编码过程带来极大的不便。 81 | 2)作用于数组的for-in循环体除了遍历数组元素外,还会遍历自定义属性。 82 | 举个例子,如果你的数组中有一个可枚举属性myArray.name,循环将额外执行一次,遍历到名为“name”的索引。就连数组原型链上的属性都能被访问到。 83 | 3)最让人震惊的是,在某些情况下,这段代码可能按照随机顺序遍历数组元素。 84 | 4)简而言之,for-in是为普通对象设计的,你可以遍历得到字符串类型的键,因此不适用于数组遍历。 85 | (4)强大的for-of循环 86 | ``` 87 | for (var value of myArray) { 88 | console.log(value); 89 | } 90 | 1)这是最简洁、最直接的遍历数组元素的语法; 91 | 2)这个方法避开了for-in循环的所有缺陷 ; 92 | 3)与forEach()不同的是,它可以正确响应break、continue和return语句 ; 93 | 4)for-of循环也可以遍历其它的集合,for-of循环不仅支持数组,还支持大多数类数组对象,例如DOM NodeList对象; 94 | 5)for-of循环也支持字符串遍历,它将字符串视为一系列的Unicode字符来进行遍历。 95 | #5、字符串的扩展 96 | 1)、ES6提供了3中新方法来确定一个字符串是否包含在另一个字符串中: 97 | (1)contains():返回布尔值,表示是否找到了参数字符串 98 | (2)startsWith():返回布尔值,表示参数字符串是否在源字符串的头部 99 | (3)endsWith():返回布尔值,表示参数字符串是否在源字符串的尾部 100 | 例如: 101 | var s = "Hello world!"; 102 | s.startsWith("Hell");//true 103 | s.endsWith("!");//true 104 | s.contains("o");//true 105 | 106 | 以上三个函数都支持第二个参数,表示开始搜索的位置 107 | s.startsWith("o",4);//true 108 | s.endsWith("e",2);//true 109 | 2)repeat() 110 | 返回一个新的字符串,表示将原字符串重复n次 111 | "x".repeat(3);//"xxx" 112 | 3) 模板字符串 113 | 模板字符串是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。 114 | //普通字符串 115 | `Hello World`; 116 | //多行字符串 117 | `Hello 118 | World!` 119 | //字符串中嵌入变量 120 | var name = 'Bob',time = "today"; 121 | `Hello ${name},how are you ${time}?`; 122 | 在模板字符串中嵌入变量,需要将变量名写在${}中。 123 | 124 | #6、数值的扩展 125 | (1) Number.isFinite() 和 Number.isNaN() 126 | 用来检查Infinite和NaN这两个特殊值 127 | 这两个方法仅对数值有效,对于飞数值一律返回false。 128 | Number.isFinite("25");//false 129 | isFinite("25");//true 130 | (2) Number.parseInt() ,Number.parseFloat() 131 | ES6将全局方法parseInt()和parseFloat()移植到了Number对象上,这样做的目的是逐步减少全局方法,使语言逐步模块化。 132 | (3) Math的扩展 133 | Math.trunc() //用于去除一个数的小数部分,返回其整数部分 134 | #7、数组的扩展 135 | (1) Array.of()//用于将一组值转换为数组 136 | Array.of(1,2,3) //[1,2,3] 137 | (2) find() //用于找出第一个符合条件的数组元素,它的参数是一个回调函数,所有数组元素依次遍历该回调函数,直到找出第一个返回值为true的元素,然后返回该元素,否则返回undefined。 138 | 139 | [1,,5,10,15] .find(function (value,index,arr) { 140 | return value > 9; 141 | }) //10 142 | findIndex()//返回第一个符合条件的数组元素的位置,如果所有元素都不符合,则返回-1 143 | (3) fill() //使用给定值填充一个数组 144 | **(4) 数组推导** 145 | 数组推导:允许直接通过现有数组生成新数组。 146 | var a1 = [1,2,3,4]; 147 | var a2 = [for (i of a1) i*2];//[2,4,6,8] 148 | for of 后面还可以附加if语句,用来设定循环的限制条件 149 | var years = [2000,2004,2008,2012,2016]; 150 | [for (year of years) if (year >2007)];//[2008,2012,2016] 151 | [for (year of years) if(year>2007&& year<2013)];//[2008,2012] 152 | #8、函数的扩展 153 | (1) 为函数的参数设置默认值。 154 | function Point (x=0,y=0) { 155 | this.x = x; 156 | this.y = y; 157 | } 158 | 任何带有默认值的参数,都被是为可选参数,不带默认值的参数,则被视为必需参数 159 | (2)rest参数 160 | ES6引入了rest参数(...变量名),用于获取函数的多于参数,rest参数后面不能再有其他参数,否则会报错。 161 | function add(...values){ 162 | let sum = 0; 163 | for(var value of values) { 164 | sum +=value; 165 | } 166 | return sum; 167 | } 168 | add(2,5,3);//10 169 | (3)扩展运算符... 170 | 扩展运算符好比rest参数的逆运算,将一个数组转换为用逗号分隔的参数序列。 171 | var a=[1]; 172 | var b=[2,3]; 173 | var c=[4,5,6]; 174 | var d=[0,...a,...b,...c]; 175 | console.log(d);//[0,1,2,3,4,5,6]; 176 | (4)箭头函数=> 177 | var f = v => v; 178 | 等同于: 179 | var f = function (v) { 180 | return v; 181 | }; 182 | var f = () => 5; 183 | 等同于:var f = function (){ 184 | return 5; 185 | } 186 | 简化函数: 187 | [1,2,3].map(function(x){ 188 | return x*x; 189 | }); 190 | //箭头函数写法 191 | [1,2,3].map(x=>x*x); 192 | 注意: 193 | 函数体内的this对象,绑定定义时所在的对象,而不是使用时所在的对象; 194 | 不可以当作构造函数,即不可以使用new命令,否则报错; 195 | 不可以使用arguments对象,该对象在函数体内不存在; 196 | 197 | 新的知识: 198 | 1、如果箭头函数不需要参数或者需要多个参数,就是用圆括号代表参数部分 199 | 例如: var sum (num1,num2) => num1+num2; 200 | 2、如果箭头函数的代码块部分多于一条语句,就要使用大括号将其括起来,并使用return语句返回 201 | 3、如果箭头函数直接返回一个对象,必须在对象外面加上括号。 202 | var getTempItem = id => ({id:id,name:"Temp"}); 203 | 由于this在箭头函数中被绑定,所以不能用call(),apply(),bind()修改this指向 204 | #8、Set 和 Map 205 | (1) Set类似于数组,不过其成员值都是唯一的,没有重复的值。 206 | Set本身是一个构造函数,用来生成Set数据结构。 207 | 例如: 208 | var s = new Set(); 209 | [2,3,4,5,5,2,2].map(x => s.add(x)); 210 | for(i of s ){ 211 | console.log(i);//2,3,4,5 212 | } 213 | //可以用数组对set进行初始化 214 | var items = new Set([1,2,2,2,2,3]); 215 | console.log(items.size);//3 216 | Set结构的方法: 217 | add(value);delete(value);has(value);clear():清除所有成员 218 | Set结构的属性: 219 | Set.prototype.constructor:构造函数,默认就是Set函数 220 | Set.prototype.size:返回Set的成员总数 221 | //去除数组中重复元素 222 | function dedupe (array) { 223 | return Array.from(new Set(array)); 224 | } 225 | (2) Map结构,类似于对象,也是键值对的集合,但是,“键”的范围不限定于字符串,对象也可以当作键。 226 | 例如: 227 | var m = new Map(); 228 | o = { 229 | p:"Hello World!"; 230 | } 231 | m.set(o,"content"); 232 | console.log(m.get(o));//content 233 | Map的属性: 234 | size:返回成员总数; 235 | Map的方法: 236 | set(key,value);get(key);has(key);delete(key);clear() 237 | Map的遍历 238 | map.keys():返回键名的遍历器 239 | map.values():返回键值的遍历器 240 | map.entries():返回所有成员的遍历器 241 | #9、Iterator遍历器 242 | 遍历器是一种协议,任何对象只要部署了这个协议,就可以完成遍历操作。它的主要作用有两个, 243 | 一个是为遍历对象的属性提供统一的接口,二是时对象的属性能够按次序排列。 244 | ES6的遍历器协议规定,部署了next方法的对象,就具备了遍历器功能。next方法必须返回一个包含value和done两个属性的对象。value属性是当前遍历位置的值,done属性是一个布尔值,表似乎遍历是否结束。 245 | function makeIterator (array) { 246 | var nextIndex = 0; 247 | return { 248 | next: function () { 249 | return nextIndex < array.length ? {value:array[nextIndex++],done:false}:{value:undefined,done:true}; 250 | } 251 | } 252 | }//定义了一个makeIterator函数,作用是返回一个遍历器对象,用来遍历参数数组。 253 | ES6中,一个对象只要部署了next方法,就被视为具有Iterator接口,就可以用for...of循环遍历它的值。 254 | var it = makeIterator([1,2,3,4,5]); 255 | for(var n of it) { 256 | if(n>it.length){ 257 | break; 258 | } 259 | console.log(n); 260 | } 261 | for...in 循环读取键名;for...of循环读取键值 262 | #10、Generator 263 | Generator 就是普通函数,有两个特征:一是function关键字后面有一个星号;二是函数体内部使用yield语句定义遍历器的每个成员,即不同的内部状态 264 | function* helloWorldGenerator () { 265 | yield 'hello'; 266 | yield 'world'; 267 | return 'ending'; 268 | } 269 | var hw = helloWorldGenerator(); 270 | hw.next(); 271 | hw.next(); 272 | hw.next(); 273 | 274 | Generator的本质,是提供一种可以暂停执行的函数。 275 | #11、Promise 276 | ES6原生提供Promise对象。所谓Promise对象,就是代表了未来某个将要发生的事件(通常是一个异步操作)。它的好处在于,有了promise对象,就可以将异步操作的流程表达出来,避免了层层嵌套的回调函数。 277 | 278 | Promise对象的基本用法: 279 | var promise = new Promise(function(resolve,reject) { 280 | if(/*异步操作成功*/) { 281 | resolve(value); 282 | } else { 283 | reject(error); 284 | } 285 | }); 286 | promise.then(function (value) { 287 | //success 288 | },function(value){ 289 | //failure 290 | }) 291 | 292 | 以上代码表示,Promise 构造函数接受一个函数作为参数,该函数的两个参数分别为resolve方法和reject方法。如果异步操作成功,则用resolve方法将Promise对象的状态变为成功,否则,用reject方法将状态变为失败。 293 | promise实例生成以后,可以使用then方法分别制定resolve方法和reject方法的回调函数。 294 | 用Promise对象实现Ajax操作: 295 | var getJSON = function (url) { 296 | var promise = new Promise (function (resolve,reject) { 297 | var client = new XMLHttpRequest(); 298 | client.open("GET",url); 299 | client.onreadystatechange = handler; 300 | client.responseType = "json"; 301 | client.setRequestHeader("Accept","application/json"); 302 | client.send(); 303 | function handler () { 304 | if (this.readyState === this.DONE) { 305 | if(this.status === 200) { 306 | resolve(this.response); 307 | } else { 308 | reject(this); 309 | } 310 | } 311 | } 312 | }); 313 | return promise; 314 | }; 315 | 316 | getJSON("/post.json").then(function(json){ 317 | //continue 318 | }, function(error){ 319 | //handle errors 320 | }) 321 | 322 | Promise 对象有三种状态: 323 | 324 | (1)Fulfilled 可以理解为成功的状态 325 | (2)Rejected 可以理解为失败的状态 326 | (3)Pending 既不是 Fulfilld 也不是 Rejected 的状态,可以理解为 Promise 对象实例创建时候的初始状态 327 | 328 | 329 | Promise.all 可以接收一个元素为 Promise 对象的数组作为参数,当这个数组里面所有的 Promise 对象都变为 resolve 时,该方法才会返回。 330 | Promise 迷你书: 331 | http://liubin.org/promises-book/ --------------------------------------------------------------------------------