function after(times,callback){
return function(){
if(--times === 0){
callback()
}
}
}
let fn = after(3,function(){
console.log('我被調用三次了')
})
fn();
fn();
fn();//我被調用三次了
複製代碼
--time
而不是time--
否則函數運行就會少執行一次。實現一個函數, 3s後才能獲取結果ajax
function run(){
setTimeout(()=>{
let text = 'runing'
//return
},3000)
}
run()
複製代碼
咱們發如今異步環境中 調用函數根本讀取不到值,使用
return
也是一樣的效果 因此解決異步 咱們就要經過傳函數的方式來執行數組
function run(callback){
setTimeout(()=>{
let text = 'runing'
//return
callback(text)
},3000)
}
run(function(text){
console.log(text) //running
})
複製代碼
從兩個例子中咱們發現,每一次的執行callback,函數就要傳參一個函數,從而會致使這樣異步
function run(callback){
setTimeout(()=>{
let text = 'runing'
//return
callback(text)
},3000)
}
run(function(text){
console.log(text) //running
run(function(text){
console.log(text+'2') //running2
run(function(text){
console.log(text+'3') //running3
})
})
})
複製代碼
在執行一次以後我還想在執行一次函數,就會出現多層嵌套(回調地獄),代碼不美觀,且若是當中一環出現了異常,咱們也很差捕獲異常函數
let numList = [];
function run(num){
setTimeout(()=>{
numList.push(num)
},3000)
}
run(1)
run(2)
console.log(numList) //輸出[]
複製代碼
咱們發現最後結果爲空數組,由於兩次的調用都是爲異步 如今咱們進行修改一下ui
let numList = [];
function after(times,callback){
return function(){
if(--times === 0){
callback(numList)
}
}
}
let fn = after(2,function(data){
console.log(data)
})
function run(num){
setTimeout(()=>{
numList.push(num)
fn();
},3000)
}
run(1)
run(2)
複製代碼
咱們發現 在
numList.length === 2
中2不能手動配置,假如我有一百個方法執行,那麼就要去改 一旦基數不許,這個方法就掛了 因此能夠借鑑咱們以前寫的after
方法this
let numList = [];
function after(times,callback){
return function(){
if(--times === 0){
callback(numList)
}
}
}
let fn = after(2,function(data){
console.log(data)
})
function run1(num){
setTimeout(()=>{
numList.push(num)
fn();
},3000)
}
function run2(num){
setTimeout(()=>{
numList.push(num)
fn();
},3000)
}
run1(1)
run2(2)
複製代碼
咱們寫了一個方法,統一收集異步結果的邏輯 可是咱們代碼寫的不是很美觀spa
let numList = [];
let Dep = {
arr:[],
on(fn){
this.arr.push(fn)
},
emit(){
if(numList.length === 2){
this.arr.forEach(function(fn){
fn();
})
}
}
}
Dep.on(function(){
console.log(numList) //[1,2]
})
Dep.on(function(){
console.log('代碼執行結束了')
})
function run1(num){
setTimeout(()=>{
numList.push(num)
Dep.emit();
},3000)
}
function run2(num){
setTimeout(()=>{
numList.push(num)
Dep.emit();
},3000)
}
run1(1)
run2(2)
複製代碼
上面邏輯 咱們完成了 將須要發佈的內容保存到隊列裏 在發佈時讓數組中的函數依次執行code
🤗🤗🤗新手本身的理解。勿噴。隊列