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);
复制代码