Promise对象的一些特性,简单来说就是:
1.成功状态调用resolve()方法,失败调用reject()方法
2.可以用throw 抛出失败信息;
3.执行函数可执行异步任务(比如ajax请求),但是执行函数(resolve,reject)=>{ 异步任务 },是同步执行的;
4.Promise状态只能修改一次,初始状态是pending;由pending-->resolve或者reject;
5.then方法,的两个回调函数(成功或者失败)
/* 1.声明构造函数 */
function Promise(executor) {
//4.添加属性
this.PromiseState = 'pending';
this.PromiseResult = null;
/* 9.异步任务 ,声明属性*/
this.callback = {};
//保存实例对象的this
const self = this;
//3.执行器函数中的参数是两个函数
/* 声明resolove函数
*/
function resolve(data) {
/* 6.promise状态只能更改一次,所以在调用
resolve和reject函数时,需要判断promise状态 */
if(self.PromiseState !== 'pending') return
self.PromiseState = 'fulfilled';
self.PromiseResult = data;
//9.调用成功的回调函数
if (self.callback.onResolved) {
self.callback.onResolved(data);
}
};
/* 声明reject函数 */
function reject(data) {
if(self.PromiseState !== 'pending') return
self.PromiseState = 'rejected';
self.PromiseResult = data;
//9.调用失败的回调函数
if (self.callback.onRejected) {
self.callback.onRejected(data);
}
};
/* 5.try--catch来完成抛出异常的处理 */
try {
/* 2.同步调用[执行器函数] */
executor(resolve, reject);
} catch (e) {
reject(e)
}
}
//7.原型添加then属性
//then方法是由两种状态的,所以要判断promiseState
Promise.prototype.then = function (onResolved, onRejected) {
//8.通过promiseState的值来判断成功还是失败
if (this.PromiseState === 'fulfilled') {
onResolved(this.PromiseResult)
};
if (this.PromiseState === 'rejected') {
onRejected(this.PromiseResult)
};
//9.判断pending 状态
if (this.PromiseState === 'pending') {
//9.在原型身上保存回调函数
this.callback = {
onResolved: onResolved,
onRejected: onRejected
}
}
}
创建一个Promise对象实例来验证:
<script>
let p = new Promise((resolve, reject) => {
// resolve('ok')
//抛出异常
// throw 'error'
/* 状态只能修改一次 */
// resolve('ok22'); //只会执行一次状态修改
// reject('err')
//9.异步任务,then方法实现
setTimeout(() => {
reject('异步回调成功')
}, 1000);
})
// console.log(p);
p.then(res => {
console.log(res);
}, reason => {
console.log(reason);
})
// console.log(p);
</script>