Promise是异步编程回调的一种解决方案,在异步执行的流程中,把执行代码和处理结果的代码清晰地分离了,基于promise我们可以把复杂的异步回调处理方式进行模块化
其内部有三个状态,分别是pending,fulfilled和rejected,且只能由pending向其它两个状态转化
Promise对象拥有两个实例方法then()和catch()
下面是ajax请求改为promise的写法:
getData(method, url){
var promise = new Promise(function(resolve, reject){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open(method, url);
xmlHttp.send();
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState == 4){
if (xmlHttp.status == 200 ) {
resolve(xmlHttp.response);
} else {
reject(xmlHttp.statusText);
}
}
};
xmlHttp.onerror = function () {
reject(xmlHttp.statusText);
};
})
return promise;
}
getData('get','www.xxx.com').then(successFun, failFun)
成功和失败的回调函数我们通过then()添加,在promise状态改变时分别调用。promise构造函数中通常都是异步的,所以then方法往往都先于resolve和reject方法执行。所以promise内部需要有一个存储fulfill时调用函数的数组和一个存储reject时调用函数的数组。
then方法可以接收两个参数,且通常都是函数。第一个参数会添加到fulfill时调用的数组中,第二个参数添加到reject时调用的数组中。当promise状态fulfill时,会把resolve(value)中的value值传给调用的函数中,同理,当promise状态reject时,会把reject(reason)中的reason值传给调用的函数
setTimeout(function(){console.log(4)},0);
new Promise(function(resolve){
console.log(1)
for( var i=0 ; i<10000 ; i++ ){
i==9999 && resolve()
}
console.log(2)
}).then(function(){
console.log(5)
});
console.log(3);
结果:1,2,3,5,4