catch 不会中断 promise ,可以继续向后传。
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('循环引用'));
}
if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
let called; // 防止被多次调用 resolve reject
try { // 防止取then是出现异常 Object.defineProperty
let then = x.then; // 取x的then方法 {then:{}}
if (typeof then === 'function') { // 如果then是函数我就认为 x 是个promise
// call 第一个参数是 this ,后面的是成功的回调和失败的回调
then.call(x, y => { // 如果y是promise就继续递归解析promise
if (called) return;
called = true;
/*
p.then(()=>{
return new Promise((resolve,reject)=>{
resolve(new Promise())
})
})
*/
resolvePromise(promise2, y, resolve, reject);
}, r => { // 只要失败了就失败了
if (called) return;
called = true;
reject(r);
});
} else { // then是一个普通对象,就直接成功即可1
resolve(x);
}
} catch (e) {
if (called) return;
called = true;
reject(e);
}
} else { // x = 123
resolve(x); // x就是一个普通值
}
}
class Promise {
constructor(executor) {
this.status = 'pending';
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks = [];
this.onRejectedCallbacks = [];
let resolve, reject
resolve = (data) => {
// 如果 resolve 里面是一个 Promise ,注册then里面的方法。
if(value instanceof Promise){
return value.then(resolve,reject)
}
if (this.status === 'pending') {
this.value = data;
this.status = 'resolved';
this.onResolvedCallbacks.forEach(fn => fn());
}
}
reject = (reason) => {
if (this.status === 'pending') {
this.reason = reason;
this.status = 'rejected';
this.onRejectedCallbacks.forEach(fn => fn());
}
}
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
then(onFulFilled, onRejected) {
// 值的穿透 p.then().then().then(data=>{console.log(data)})
onFulFilled = typeof onFulFilled === 'function' ? onFulFilled : y => y;
onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; };
let promise2;
if (this.status === 'resolved') {
promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
try {
let x = onFulFilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
}
if (this.status === 'rejected') {
promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject)
} catch (e) {
reject(e);
}
}, 0);
});
}
if (this.status === 'pending') {
promise2 = new Promise((resolve, reject) => {
this.onResolvedCallbacks.push(() => {
setTimeout(() => {
try {
let x = onFulFilled(this.value);
resolvePromise(promise2, x, resolve, reject)
} catch (e) {
reject(e);
}
}, 0)
});
// 存放失败的回调
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
}, 0);
});
})
}
return promise2; // 调用then后返回一个新的promise
}
// catch接收的参数 只用错误
catch(onRejected) {
// catch就是then的没有成功的简写
return this.then(null, onRejected);
}
}
Promise.resolve = function (val) {
return new Promise((resolve, reject) => resolve(val))
}
Promise.reject = function (reason) {
return new Promise((resolve, reject) => reject(reason));
}
// 有一个失败就失败,有一个成功就成功
Promise.race = function (promises) {
return new Promise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
// 判断下是否是 promise
let current = promises[i]
if((typeof current === 'object' && current !== null) || typeof current === 'function'){
if(typeof current.then === 'function'){
current.then(resolve,reject)
}else{
resolve(current);
}
}else{
resolve(current);
}
}
});
}
// 有一个失败直接失败,全部成功才成功
Promise.all = function (promises) {
return new Promise((resolve,reject)=>{
let result = [];
let i = 0; // i的目的是为了保证获取全部成功,来设置的索引
function processData(index,data) {
result[index] = data;
i++;
if (i === promises.length){
resolve(result);
}
}
for(let i = 0;i<promises.length;i++){
// 判断下是否是 promise
let current = promises[i]
if((typeof current === 'object' && current !== null) || typeof current === 'function'){
if(typeof current.then === 'function'){
current.then(data=>{
processData(i,data);
},reject)
}else{
processData(i,current);
}
}else{
processData(i,current);
}
}
})
}
// 使用 promise A+ 测试
// 延迟对象 deferred
Promise.deferred = Promise.defer = function () {
let dfd = {};
dfd.promise = new Promise((resolve, reject) => {
dfd.resolve = resolve;
dfd.reject = reject;
})
return dfd;
}
module.exports = Promise;
上面暴露的 Promise.deferred 延迟对象使用:
function read(url){
let dfd = Promise.defer()
fs.readFile(url,'utf8',(err,data)=>{
if(err) dfd.reject(err)
dfd.resolve(data)
})
return dfd.promise
}
read('1.txt').then(data=>{
console.log(data)
})
看下面代码,输出什么?
const p = Promise.resolve();
(async () => {
await p;
console.log("after:await");
})();
p.then(() => {
console.log("tick:a");
}).then(() => {
console.log("tick:b");
});
在新版本的浏览器跟node 版本中都是下面的输出:
tick:a
tick:b
after:await
那为什么 tick a 会比 after:await 快呢?我们把 async 函数转成 promise 就容易理解了:
const p = Promise.resolve();
(() => {
const implicit_promise = new Promise(resolve => {
const promise = new Promise(res => res(p));
promise.then(() => {
console.log("after:await");
resolve();
});
});
return implicit_promise;
})();
p.then(() => {
console.log("tick:a");
}).then(() => {
console.log("tick:b");
});
上面的输出就是: tick:a tick:b after:await
那如果在 p 后面再加一个 then 呢?如下:
const p = Promise.resolve()
;(() => {
const implicit_promise = new Promise(resolve => {
const promise = new Promise(res => res(p))
promise.then(() => {
console.log('after:await')
resolve()
})
})
return implicit_promise
})()
p.then(() => {
console.log('tick:a')
}).then(() => {
console.log('tick:b')
}).then(()=>{
console.log('tick:c')
})
上面的输出就是: tick:a tick:b after:await tick:c
分析:
new Promise(res => res(p)) 中 res(p) 这个 p = Promise.resolve() 是立即成功的,就会立马调用 p.then 的 tick:a ,由于这个 then 没有返回值,立即往微任务队列放入 tick:b ,相当于 x = p.then(()=>{console.log(‘tick:a’)});x.then(()=>{console.log(“tick:b”)});在调用了 tick:a 这个 then 后, promise 这个 Promise 就执行成功了,所以 after:await 这个 promise.then 会跟在 tick:b 之后放入微任务队列。最后才是 tick:c。