計數器方式實現異步併發

callback - 經過計數器的方式實現多異步併發

經過最原始方式實現異步多併發bash

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);

複製代碼
相關文章
相關標籤/搜索