异步相关知识总结:
异步的解决方案(promise的原理、基本应用、promise的标准)async/await(es7标准 和promise的区别、联系)总结当前JS异步的解决方案★异步的解决方案(promise) 1.promise基本语法(es6) 2.异常捕获 3.多个串联(顺序来执行) 4.promise.all和promise.race 5.promise标准及状态变化
promise基本语法(es6):
function loadImg(src) { const promise = new Promise(function (resolve, reject) { var img = document.createElement("img"); img.onload = function (img) { resolve(); }; img.onerror = function () { reject(); }; img.src = src; }); return promise } var src = "https://i01picsos.sogoucdn.com/7de1f843a8b82410"; var result = loadImg(src); //result是promise对象 result.then(function (img) { console.log(img.width); }, function () { console.log("error1"); }).then(function (img) { console.log(img.height); });异常捕获:
var src = "https://i01picsos.sogoucdn.com/7de1f843a8b82410"; var result = loadImg(src); //result是promise对象 result.then(function (img) { console.log(img.width); }).then(function (img) { console.log(img.height); }).catch(function(er){ //不管有多少个then,后面跟一个catch,参数为异常,统一异常捕获 console.log(ex); });catch捕获异常,可以捕获到语法错误,即逻辑之外的错误,也可以通过给reject传参,捕获到逻辑之内的错误。 注意:异常捕获规定then只能接受一个参数,最后统一用catch捕获异常(失败或者是报异常)
promise多个串联
promise多个串联经常在ajax中用到,比如:得先拿到用户的信息才能去查找用户的好友、用户聊天记录等信息
用图片模拟这个场景:
var src1 = "https://i04picsos.sogoucdn.com/a64beecbeacd7e58"; result1 = loadImg(src1); var src2 = "https://i04picsos.sogoucdn.com/08bace7dedbf47e0"; result2 = loadImg(src2); //链式操作 result1.then(function (img1) { console.log("第一个图片加载完成", img1.width); return result2 //!!!!重要 }).then(function (img2) { console.log("第二个图片加载完成", img2.width); }).catch(function (ex) { console.log(ex); //统一异常捕获 });promise.all & promise.race
Promise.all([result1,result2]).then(function(datas){ //接收到的datas是一个数组,依次包含多个promise返回的内容 console.log(datas[0]); console.log(datas[1]); }); Promise.race([result1,result2]).then(function(data){ //data即最先执行完成的promise的返回值 console.log(data); }); promise.all & promise.race都接收一个包含多个promise对象的数组promise.all是待全部完成之后,统一执行success,promise.race只要有一个完成,就执行successpromise标准及状态变化
任何技术推广都需要一套标准来支撑,如html css http等,无规矩不成方圆任何不符合标准的东西,终将被用户抛弃,不要挑战标准,不要自造标准promise标准—状态变化:
三种状态:pending fulfilled rejected初始状态pendingpending变成fulfilled(成功),pending变成rejected(失败)状态变化不可逆promise标准—then
promise必须实现then这个方法then()必须可以接受两个函数作为参数then返回的必须是一个promise实例 (下一个.then的对象是第一个.then返回的promise实例,若上一个.then没有明确写.then,则返回本身的promise实例)★async/await(es7标准 与promise的区别、联系) async/await是es7标准,babel现已支持,并没有和promise冲突,相当于promise的扩展。
promise.then只是将callback拆分了,async/await是最直接的同步写法 jQuery 1.5之前是callback的形式,jQuery 1.5之后.then只是将callback拆分了
async和await的语法:
使用await,函数必须有async标识await后面跟的是一个promise实例使用了promise,并没有和promise冲突完全是同步的写法,再也没有回调函数需要import “babel-polyfill”但是,改变不了JS异步,单线程的本质★当前JS异步的解决方案
jQuery的DeferredPromiseasync/awaitGenerator