jQuery中deferred、promise对象的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wlx1991/article/details/50756359
// 顺序执行多个异步操作
// deferred.then() 中返回一个新建的 deferred 对象
$.Deferred(function(d){
	console.log('start');
	d.resolve();
}).then(function(){
	var dfd = $.Deferred();
	
	setTimeout(function(){
		console.log('done1');;
		dfd.resolve();
	},1000);
	
	return dfd;
}).then(function(){
	var dfd = $.Deferred();
	
	setTimeout(function(){
		console.log('done2');;
		dfd.resolve();
	},1000);
	
	return dfd;
}).done(function(){
	console.log('finish');
});



// 传递异步操作的返回值
$.Deferred(function(d){
	d.resolve([]);
}).then(function(arr){
	arr.push(1);
	console.log(arr);
	return arr;
}).then(function(arr){
	arr.push(2);
	console.log(arr);
	return arr;
}).then(function(arr){
	arr.push(3);
	console.log(arr);
	return arr;
}).done(function(arr){
	console.log(arr);
});
/*
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3]
*/


// 监听多个异步操作完成后再执行目标操作
$.when(function(){
	var dfd = $.Deferred();
	
	setTimeout(function(){
		console.log(1);
		dfd.resolve();
	}, 1000);
	
	return dfd;
}(), function(){
	var dfd = $.Deferred();
	
	setTimeout(function(){
		console.log(2);
		dfd.resolve();
	}, 2000);
	
	return dfd;
}()).then(function(){
	console.log('done');
},function(){
	console.log('fail');
});


猜你喜欢

转载自blog.csdn.net/wlx1991/article/details/50756359
今日推荐