1、Promise的特点
a、Promise是异步编程的一种解决方案。
b、Promise的状态不受外部影响,一旦建立就会立即执行,无法中途取消;
c、一旦状态发生改变之后就不会改变。
2、Promise状态
a、pending(操作进行中),在此时无法得知目前处于哪个阶段(是开始还是完成阶段);
b、fulfilled(已经完成),也可以是resolve阶段;
c、rejected(已经失败)
3、promise实例
- 下面以封装的ajax请求为基础来对Promise构造函数和promise对象进行解读。
function httpPost (url,params) {
params = JSON.stringify(params);
function Cons (resolve,reject) {
const handler = function () {
if (this.readyState !== 4) {
return
}
if (this.status === 200 || this.status === 304) {
resolve(this.response);
} else {
reject(new Error(this.statusText))
}
}
const xhr = new XMLHttpRequest();
xhr.open("POST",url);
xhr.onreadystatechange = handler;
xhr.resposeType = 'json';
xhr.setRequestHeader('Accept','application/json');
xhr.send(params);
}
const promiseObj = new Promise(Cons);
return promiseObj;
}
httpPost('http://game.bizpartner.cn/gamePrizeActivity/findZiGe',{type: 'ch',page:1,token:"4979f69dabe042f1b0c03a2cf696d6ce"})
.then(res=>console.log(res))
.catch(err=>console.log(err))
- 以上代码解读:
1、promise对象的then方法的参数有两个,一个是resolve状态下的回调,另一个是rejected状态下的回调。rejected状态下的回调是可以省略掉的。
2、因为then返回的是一个新的promise函数,所以可以使用链式方法来写。代码如下:
httpPost('/game2',{type:2})
.then(function(resolve){
console.log('请求成功');
})
.then(function(reject){
console.log('请求失败');
})
b、catch
Promise.prototype.catch()
httpPost('/game2',{type:2})
.then(function(resolve){
console.log('请求成功');
})
.catch(function(reject){
console.log('请求失败');
})
// 该方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数。回调中抛出错误,也会被catch方法捕获。
c、resolve
Promise.resolve()
//如果有需要将对象转化为Promise对象,Promise.resolve();
Promise.resolve(console.log('oo'));
||
|| 等价于
VV
new Promise(resolve=>console.log('pp'));
d、reject
Promise.reject()
//该方法返回的也是一个新的promise实例,该实例的状态是rejected。
const thenable = {
then(resolve, reject) {
reject('出错了');
}
};
Promise.reject(thenable)
.catch(e => {
console.log(e === thenable)
})
原创作者连接:https://blog.csdn.net/jiuwanli666/article/details/80082821#commentBox