callback - 通過計數器的方式實現多非同步併發
通過最原始方式實現非同步多併發
let times = 3;
let obj = {};
function out(obj){
times--;
if(times === 0){
console.log(obj);
}
}
setTimeout(()=>{
obj['name'] = 'Yizhong';
out(obj);
}, 2000);
setTimeout(()=>{
obj['age'] = '33';
out(obj);
}, 3000);
setTimeout(()=>{
obj['address'] = 'Hefei';
out(obj);
}, 4000);
複製程式碼
通過高階函式(閉包)方式優化實現
function after(times, callback){
return function(obj){
if(--times === 0){
callback(obj);
}
};
}
let obj = {};
let out = after(3, function(obj){
console.log(obj);
});
setTimeout(()=>{
obj['name'] = 'Yizhong';
out(obj);
}, 2000);
setTimeout(()=>{
obj['age'] = '33';
out(obj);
}, 3000);
setTimeout(()=>{
obj['address'] = 'Hefei';
out(obj);
}, 4000);
複製程式碼