ES6中的 Promise 是异步编程的一种解决方案。Promise是一个对象,从Promise中,可以获取异步操作的消息从而对异步操作进行响应。Promise可以将异步操作以同步操作的流程表现出来,避免了嵌套回调函数可能出现的问题。不过Promise也存在着一定的问题,例如Promise是无法中途取消的,并且如果不设置回调函数,或者使用catch方法,那么Promise内部出现的错误是不会被反应出来的。
Promise对象主要有三种描述状态,Pending(进行中),Resolved(已完成)和Rejected(已经失败)。Promise对象的状态不受外界的影响,异步操作的结果决定了Promise处于何种状态。并且一旦Promise的状态发生改变,那么任何操作都无法再改变它。
var promise = new Promise(function(resolve,reject){
});
promise.then(function(success){
/*
* code
*/
},function(error){
/*
*code
*/
});
从上面的例子中,我们可以看到,Promise构造函数接受了一个函数作为参数。该函数带有两个参数,resolve和reject。这两个参数同样也是函数,resolve函数的作用用来在异步操作成功时,将成功的结果作为参数传递出去给then方法。reject函数的作用用来在异步操作失败时,将失败的结果作为参数传递出去。而then方法则接受两个函数作为参数,其中第一个参数是必须的,第二个参数则可以省略。
下面我们来看一个例子。
var getJSON = function(requestUrl){
return new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open("GET",requestUrl);
xhr.responseType = "json";
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = callback;
xhr.send();
function callback(){
if (this.readyState !== 4) {
return false;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
});
}
var url = "http://campus.iot.xiaofuonline.com:8090/......;
getJSON(url).then(function(response){
console.log("response = " + JSON.stringify(response));
},function(error){
console.log("error = " + error);
});
在上面的例子中,我们封装了一个http请求。当请求成功时,调用resolve函数,请求失败时,调用reject函数,两个函数都带有对应的参数,这两个参数都会被传递给对应的回调函数。
当然我们并不建议说在then方法中去捕获错误,比如我们嵌套了两个异步操作的话。
getJSON(url).then(function(response){
console.log(JSON.stringify(response));
return getJSON(url);
},function(error){
console.log(error);
}).then(function(res){
console.log(JSON.stringify(res));
},function(error){
console.log(error);
});
这样将变得异常麻烦,好在Promise为我们提供了一个catch方法。上述中嵌套的任何一个异步操作抛出的错误都将会被catch最后捕获。
举个例子 为了方便 下面用到了箭头函数。
var err = function(){
return new Promise((resolve,reject) => {
reject('error');
});
}
getJSON(url).then((response) => {
console.log('success');
return err();
}).catch((error) => {
console.log(error);
});
Promise 还提供了几个比较常用的方法,比如all()方法。all方法只有在所有的promise实例的状态都变为resolve后才会触发resolve函数,只要有任何一个的状态是reject的,那么就会立刻触发reject函数。
var p = [1000,2000,3000].map((ms)=>{
return new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log(ms);
resolve();
},ms);
});
});
Promise.all(p).then(()=>{
console.log("success ==");
}).catch(()=>{
console.log('error');
});
今天之所以提到了Promise,主要是为了后面jQuery源码Deferred模块提供一些基础知识。