异步
- 什么是单线程,和异步有什么关系?
单线程是指同一时间只能做一件事,避免DOM渲染冲突,异步是解决单线程最佳方案。webworker支持多线程,但不能访问DOM。setTimeout、setInterval为异步代码。
- 什么是event-loop?
指事件轮循,主进程先执行同步代码,异步函数先放在异步队列中,待同步函数执行完毕,轮循执行异步队列的函数。
- 是否用过jQuery的deferred?
jQuery1.5后支持deferred,它是一种语法糖形式,但是解耦了代码。符合“开放封闭原则”,即开放扩展封闭修改。
var ajax = $.ajax('./data.json') ajax.done(function(){ console.log('hello') }) .fail(function(){ console.log('error') }) .done(function(){ console.log('word!') }) .done(function(){ console.log('你好') })
// 封装一个deferred函数
function waitHeandle () {
var dtd = $.Deferred()
var wait = function (data) {
var task = function () {
console.log('执行完成')
dtd.resolve()
}
setTimeout(task, 1000)
return dtd.promise()
}
return wait(dtd)
}
var w = waitHeandle()
w.then(function(){console.log('aaaaa')},function(){console.log('11111')})
w.then(function(){console.log('bbbbb')},function(){console.log('22222')})
- Promise的基本使用和原理
function loadImg(src) { var 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 = 'https://gss0.bdstatic.com/5bVWsj_p_tVS5dKfpU_Y_D3/res/r/image/2017-09-27/297f5edb1e984613083a2d3cc0c5bb36.png' var result = loadImg(src) result.then(function(img){ console.log('图片宽度:' + img.width ) return img }).then(function(img){ console.log('图片高度:' + img.height) }).catch(function(ex){ console.log(ex) })
// 串联
var src1 = 'https://gss0.bdstatic.com/5bVWsj_p_tVS5dKfpU_Y_D3/res/r/image/2017-09-27/297f5edb1e984613083a2d3cc0c5bb36.png'
var result1 = loadImg(src1)
var src2 = 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png'
var result2 = loadImg(src2)
result1.then(function(img1){
console.log('图片宽度1:' + img1.width )
return result2
}).then(function(img2){
console.log('图片宽度2:' + img2.width)
}).catch(function(ex){
console.log(ex)
})
// async、await写法
var src1 = 'https://gss0.bdstatic.com/5bVWsj_p_tVS5dKfpU_Y_D3/res/r/image/2017-09-27/297f5edb1e984613083a2d3cc0c5bb36.png'
var src2 = 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png'
const load = async function() {
const result1 = await loadImg(src1)
console.log(result1)
const result2 = await loadImg(src2)
console.log(result2)
}
load()