专业的编程技术博客社区

网站首页 > 博客文章 正文

ES6中 promise 介绍(es6 promise作用)

baijin 2024-10-27 19:20:48 博客文章 11 ℃ 0 评论

promise 相当于一个规范 解决js中多个一步回调优化/维护...的问题。

原生中提供了promise对象,es6中promise对象是一个构造函数,用来生成promise实例。

const promise=new Promise(function(resolve,reject){

	resolve(1);

})
接受一个函数作为参数,二个参数 由js引擎提供,不用自己部署
resolve 的作用是promise对象的状态从未完成到成功,成功后,将异步操作的结果作为参数传递;
reject 的作用是promise对象的状态从未完成到失败,失败后,将异步操作的结果作为参数传递;

then()方法分别制定resolve reject状态的回调函数

jquery defrred 就是jquery中promise的实现

const getJSON=function(url,type,data){
	const promise=new Promise(function(resolve,reject){	
		let xml=new XMLHttpRequest();
		xml.open(type,url);
		if(type=='get'){
			xml.send();
		}else{
			xml.setRequestHeader('Content-type','applicateion/json');
			xml.send(JSON.stringify(data));
		}
 
		const handler=function(){
		if(xml.readyState==4 && xml.status==200){
			resolve();
		}else{
			reject();
		}
		xml.onreadystatechange=handler;
		}
	})


}

let list= (name,msg) =>{

	getJSON('http://localhost:3000/add','post',{name:name,msg:msg})

	.then(function(res){ //成功后 支持延续任务的调用,可以写多个then

		console.log(res);

	},function(error){ //失败后

		console.log(error);

	})

}

预请求:就是先测试性请求(options)

//jquery 低于1.5版本返回的是XHR对象,高于defrred对象

$.ajax({url:'',type;'get',dataType:'json'})
.done(function(res){ //done不支持延续任务的调用
	console.log(res)
})
.fail(function(error){
	console.log(error)
})

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表