1.Promise 是一对象,接收一个回调函数,该函数包含resolve和reject两个参数,在new 一个promise的时候就会执行回调函数的内容,如果函数执行正常,使用resolve返回带有data数据的promise对象,否则使用reject返回带有失败数据的promise对象。
function _Promise(excutor) {
let _this = this;
this.status = "pending";
this.onResolveCallbackedFun = [];
this.onRejectCallbackedFun = [];
this.reslut = null;
this.reason = null;
function resolve(value) {
setTimeout(() => {
if (_this.status === 'pending') {
_this.status = "resolve";
_this.reslut = value;
_this.onResolveCallbackedFun.forEach((fn) => fn(value));
}
}, 0);
}
function reject(reason) {
setTimeout(() => {
if (_this.status === "pending") {
_this.status = "reject";
_this.reason = reason;
_this.onRejectCallbackedFun.forEach((fn) => fn(reason))
}
}, 0);
}
try {
excutor(resolve, reject);
} catch (e) {
throw e;
}
}
_Promise.prototype.then = function (onFulfilled, onRejected) {
let that = this;
onFulfilled = typeof onFulfilled === 'function'?onFulfilled:value=>value;
onRejected = typeof onRejected === 'function'? onRejected :reason =>{throw reason};
if (that.status === 'resolve') {
setTimeout(() => {
onFulfilled(that.reslut);
}, 0);
}
if (that.status === 'reject') {
setTimeout(() => {
onRejected(that.reason);
}, 0);
}
if (that.status === 'pending') {
that.onResolveCallbackedFun.push(onFulfilled);
that.onRejectCallbackedFun.push(onRejected);
}
}
2.使用then和catch分别处理resolve和reject的情况。
3.await必须在async函数中使用,await后可以接promise对象的表达式,亦可以接正常返回的表达式。使用await后面的代码将不再执行并跳出此函数。如果await后面是一个promise对象,需要返回成功的值,不能处理失败的情况,需要使用try{}catch(error){}
//如何实现链式调用?
//new promise返回一个promise,then也返回一个promise,
//then 创建一个 新的 promise,如果then的回调函数返回普通值,直接resolve/reject
//如果then的回调函数返回一个新newPromise,使用新newPromise.then(resove,reject)