Promise的基本使用
1 Callback Hell
2 Promise语法
Callback Hell
function loadImg(src,callback,fail) {
var img = document.createElement("img")
img.onload = function () {
callback(img)
}
img.onerror = function () {
fail()
}
img.src = src
}
var src = "图片的地址"
loadImg(src,function(img){
console.log(img.width)
},function (){
console.log(“failed”)
})
Promise语法
var src = "图片地址"
var result = loadImg(src)
result.then(function (img) {
console.log(img.widht)
},function() {
console.log("failed")
})
result.then(function(img){
console.log(img,height)
})
Promise 语法
function LoadImg(src) {
const promise = new Promise(function(resolve,reject){
var img = document.createElement('img')
img.onload = function() {
resolve(img)
}
img.onerror = function () {
reject()
}
img.src = src
})
return promise
}
var src = "图片地址"
var result = loadImg(src)
result .then(function(img){
console.log(img.width)
},function(){
console.log('failed')
})
result.then(function(img){
console.log(img.height)
})
js中const,var,let区别
1 const 定义的变量不可以修改,而且必须初始化
const b = 2; //正确
const b //错误,必须初始化
2 var 定义的变量可以修改,如果不初始化会输出undefined,不会报错
var a = 1;
var a;//不会报错
3 let是块级作用域,函数内部使用let定义后,对函数外部无影响
let c=3;
问题解答
1 new Promise 实例,而且要return
2 new Promise时要传入函数,函数有resolve和reject两个参数
3 成功时执行resolve()失败时执行reject()
4 then监听结果
简单的ajax原生实现
var url = "https://hq.tigerbrokers.com"
var result
var XHR = new XMLHttpRequest();
XHT.open("GET",url,true);
XHR.send();
XHR.onreadystatechange = function() {
if(XHR.readyState == 4 && XHR.status == 200){
result =XHR.response
console.log(result)
}
}
总结一下ES6其他常用功能
1 let /const
2 多行字符串/模板变量
3 结构赋值
4 块级作用域
5 函数默认参数
6 箭头函数
1 let /const
//JS
var i = 10;
i = 100;
var j = 20;
j = 200;
//ES6
let i = 10;
i = 100; //正确
//const定义一个变量,这个变量就不能够修改了
const j = 20;
j = 200; //报错
2 多行字符串/模板变量
//JS
var name = "zhangsan",age = 20,html = ' ';
html+='<div>';
htm+="<p>”+name+“</p>”;
html+='</div>';
//ES6
const name = 'zhangsan' ,age = 20;
const html = ` <div>
<p>${name}</p>
<p>${age}</p>`
console.log(html)
3 解析赋值
//JS
var obj = {a:100,b:200}
var a = obj.a
var b = obj.b
var arr = ['xxxx','yyy','zzz']
var x=arr[0]
//ES6
const obj = {a:10,b:20,c:30}
const {a,c} = obj
console.log(a)
console.log(c)
const arr = ['xxxx','yyy','zzz']
const [x,y,z] = arr
console.log(x)
console.log(y)
console.log(z)
4 块级作用域
//JS
var obj = {a:100,b:200}
for(var item in obj) {
console.log(item)
}
console.log(item) //'b'
//ES6
const obj = {a:100,b:200}
for( let item in obj) {
console.log(item)
}
console.log(item) //undefined
默认参数
//JS
function (a,b) {
if(b == null) {
b = 0
}
}
//ES6
function (a,b=0) {
}
箭头函数
//JS
var arr = [1,2,3]
arr.map (function (item) {
return item+1
})
//ES6
const arr = [1,2,3]
arr.map(item => item +1);
arr.map((item,index )=> {
console.log(index)
return item +1
})
特别重要
function fn() {
console.log('real',this) //{a:100}
var arr = [1,2,3]
//普通函数
arr.map(function(item){
console.log('js',this) //window
return item+1
})
//箭头函数
arr.map(item => {
console.log('es6',this) //{a:100}
return item+1
})
}
fn.call({a:100})