异步,开放封闭原则

什么是单线程,和异步有什么关系
只能做一个线程,只能做一件事,原因是避免Dom渲染的冲突
浏览器需要渲染Dom
js可以修改DOM结构
js执行的时候,浏览器Dom渲染会停止
两段js也不能同事执行(都修改dom就冲突了)
webworker支持多线程,但是不能同时访问Dom
解决方案------异步
什么是event-loop
异步的实现方式就是event-loop
同步代码,直接执行;
异步函数先放在异步队列中
待同步函数执行完成,轮循执行异步队列中的函数

是否用过jquery的Deferred
. D e f e r r e d a p i .Deferred 的api可分为两类,用意不同 第一类: .Deferred.resolve $.Deferred.reject
第二类: $.Deferred.then $.Deferred.done $.Deferred.fail

jq1.5之后
var ajax = $.ajax(‘data.json’)
ajax.done(function() {
console.log(‘success 1’)
}).fail(function(){
console.log(‘error’)
})
.done(function(){
console.log(‘success 2’)
}).fail(function(){
console.log(‘fail 2’)
})
var ajax = $.ajax(‘data.json’)
ajax.then(function(){
console.log(‘sucess1’)
},function() {
console.log(‘fail 1’)
})
.then(function(){
console.log(‘success 2’)
},function(){
console.log(‘fail 2’)
})

function waithandle(){
var dtd = $.Deferred()
var wait = function(dtd){
var task = function() {
console.log(‘执行完成’)
dtd.resolve()
}
setTimeout(task,2000)
return dtd
}
return wait(dtd)
}
var w = waitHandle()
w.then(function(){
console.log(‘ok 1’)
},function() {
console.log(‘ok 2’)
}).then(function()
{
console.log(‘OK 2’)
},function(){
console.log(‘fail 2’)
})

Promise的基本使用和原理
基本语法回顾
必须new一个promise对象 最后必须return
promise对象必须传入一个函数,函数有两个参数一个是resolve;一个是reject;
then()监听函数的失败与成功
异常捕获
reult.then(function(img){
console.log(img.width)
}).then(function(){
console.log(img.height)
}).catch(function(ex){
console.log(ex)
})
多个串联

promise.all 和promise.race
promise.all接收一个promise对象的数组
待全部做完之后,统一执行success
promise.race接收一个promise对象的数组,只要有一个做完之后,就执行success
promise标准
三种状态不可逆。pending初始状态,fulfilled成功;rejected失败
pennding
fulfilled
rejected
Promise实例必须实现then这个方法
then()必须可以接收两个函数作为参数
then()返回的必须是一个promise实例

介绍一下async/await9和promise的区别、联系
.then只是将callback拆分了
async/await 是最直接的同步方法
使用await ,函数必须用async标识
await
后面跟一个promise实例
需要babel-polyfill
介绍一下当前js解决一步方案
单线程就是同时制作一件事,两端JS不能同时执行
圆心就是避免了DOM渲染的冲突
已不是一种无奈的解决方案
事件轮询就是异步的表现形式
promise的基本使用和原理
如何异常捕获.then().catch()
多个串联执行的好处
promise.all和promise.race
promise的标准
async、await;使用了promise,并没有和promise冲突
完全同步的写法,再也没有回调函数
但是改变不了js单线程异步的本质

猜你喜欢

转载自blog.csdn.net/qq_42259940/article/details/87195245
今日推荐