Promise、Promise.all、Promise.race
Promise 的用途
Promise代表了一个异步操作的最终完成或者失败,支持链式调用和并行多异步操作,解决地狱回调问题
地狱回调问题的产生原因
- 嵌套调用,第一个函数的输出往往是第二个函数的输入;
通过链式调用解决 - 处理多个异步请求合并最终结果
使用Promise.all
和Promise.race()
使用 Promise
构建 Promise 对象时,需要传入一个 executor
函数,该函数是立即执行的
const myFirstPromise = new Promise((resolve, reject) => {
console.log('立即执行')
resolve(data)
reject(reason)
});
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
resolve(data)
reject(reason)
});
};
链式调用
then()
函数中的返回值能在下一个then()
中获取到,这就是链式调用。不在then
中放入参数,例:promise.then().then()
,那么其后面的 then 依旧可以得到之前then
返回的值,这就是所谓的值的穿透。
then()
函数会返回一个和原来不同的新的Promise
,并把上一个then()
的返回结果传给这个新的promise
的then
方法
const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);
/*上下两种写法等价*/
const promise2 = doSomething().then(successCallback, failureCallback);
Catch 链式操作
new Promise((resolve, reject) => {
console.log('初始化');
resolve();
})
.then(() => {
throw new Error('有哪里不对了');
console.log('执行「这个」”');
})
.catch(() => {
console.log('执行「那个」');
})
.then(() => {
console.log('执行「这个」,无论前面发生了什么');
});
初始化
执行“那个”
执行“这个”,无论前面发生了什么
Promise.all
Promise.all([promise1, promise2])
并行,等待所有 promise
成功。
如果都成功了,则 all
对应的 promise
也成功;如果有一个失败了,则 all
对应的 promise
失败。
Promise.race
Promise.race([promise1, promise2])
,返回一个 promise
,一旦数组中的某个 promise
解决或拒绝,返回的 promise
就会解决或拒绝。总之,谁第先成功或失败,就认为是 race
的成功或失败。
手写 Promise
- 实现异步操作(发布订阅模式
收集依赖
->触发通知
->取出依赖
执行的方式) - 实现链式调用和值穿透
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';
const resolvePromise = (promise2, x, resolve, reject) => {
// 自己等待自己完成是错误的实现,用一个类型错误,结束掉 promise
if (promise2 === x) {
return reject(new TypeError('返回原promise引起循环调用'))
}
// 保证 resolvePromise和rejectPromise 多次调用时只调用一次
let called;
// 后续的条件要严格判断 保证代码能和别的库一起使用
if ((typeof x === 'object' && x != null) || typeof x === 'function') {
try {
// reject 和 resolve 同时调用时,只调用一个
let then = x.then;
if (typeof then === 'function') {
// 不要写成 x.then,直接 then.call 就可以了 因为 x.then 会再次取值,Object.defineProperty
then.call(x, y => { // 根据 promise 的状态决定是成功还是失败
if (called) return;
called = true;
// 递归解析(promise 中还有 promise)
resolvePromise(promise2, y, resolve, reject);
}, r => {
// 只要失败就失败
if (called) return;
called = true;
reject(r);
});
} else {
// 如果 x.then 是个普通值就直接返回 resolve 作为结果
resolve(x);
}
} catch (e) {
// //引发异常e,则promise必须拒绝
if (called) return;
called = true;
reject(e)
}
} else {
// 如果 x 是个普通值就直接返回 resolve 作为结果
resolve(x)
}
}
class Promise1 {
constructor(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks = [];
this.onRejectedCallbacks= [];
let resolve = (value) => {
if(this.status === PENDING) {
this.status = FULFILLED;
this.value = value;
this.onResolvedCallbacks.forEach(fn=>fn());
}
}
let reject = (reason) => {
if(this.status === PENDING) {
this.status = REJECTED;
this.reason = reason;
this.onRejectedCallbacks.forEach(fn=>fn());
}
}
try {
executor(resolve,reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled, onRejected) {
//解决 onFufilled,onRejected 没有传值的问题
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
//因为错误的值要让后面访问到,所以这里也要跑出个错误,不然会在之后 then 的 resolve 中捕获
onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err };
// 每次调用 then 都返回一个新的 promise
let promise2 = new Promise1((resolve, reject) => {
if (this.status === FULFILLED) {
//在引擎之后和在promise实现后调用
setTimeout(() => {
try {
//有可能返回一个promise
let x = onFulfilled(this.value);
// x可能是一个proimise
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
//引发异常e,则promise必须拒绝
reject(e)
}
}, 0);
}
if (this.status === REJECTED) {
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e)
}
}, 0);
}
if (this.status === PENDING) {
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;
}
}
const promise = new Promise1((resolve, reject) => {
setTimeout(() => {
reject('失败');
},1000);
}).then().then().then(data=>{
console.log(data);
},err=>{
console.log('err',err);
})
测试用例
const promise = new Promise1((resolve, reject) => {
setTimeout(() => {
reject('失败');
},1000);
}).then().then().then(data=>{
console.log(data);
},err=>{
console.log('err',err);
})
手写 Promise.all
function isPromise(obj) {
return ((typeof obj === 'object' && obj != null) || typeof obj === 'function') && typeof obj.then == 'function';
}
function myPromiseAll(promisesArr) {
let result = []
return new Promise((resolve, reject) => {
for (let i = 0; i < promisesArr.length; i++) {
if (isPromise(promisesArr[i])) {
promisesArr[i].then(data => {
result[i] = data;
if (result.length === promisesArr.length) {//关键点是何时"决议",也就是何时resolve出来
resolve(result)
}
}).catch(error => {
reject(error)
})
} else {
result[i] = promisesArr[i];
}
}
})
}
let p1 = Promise.resolve(3);
let p2 = 1337;
let p3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
myPromiseAll([p1, p2, p3]).then(values => {
console.log(values); // [3, 1337, "foo"]
});
Promise.race
function isPromise(obj) {
return ((typeof obj === 'object' && obj != null) || typeof obj === 'function') && typeof obj.then == 'function';
}
function myPromiseRace(promisesArr) {
return new Promise((resolve, reject) => {
for (let i = 0; i < promisesArr.length; i++) {
if (isPromise(promisesArr[i])) {
promisesArr[i].then(resolve, reject);
} else {
resolve(promisesArr[i])
}
}
});
}
let promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'one');
});
let promise2 = new Promise((resolve, reject) => {
setTimeout(reject, 100, 'two');
});
myPromiseRace([promise1, promise2]).then((value) => {
console.log(value);
// Both resolve, but promise2 is faster
});
练一练
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 1000)
})
const promise2 = promise1.then(() => {
throw new Error('error!!!')
})
console.log('promise1', promise1)
console.log('promise2', promise2)
setTimeout(() => {
console.log('promise1', promise1)
console.log('promise2', promise2)
}, 2000)
promise1 Promise { <pending> }
promise2 Promise { <pending> }
(node:50928) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: error!!!
(node:50928) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
promise1 Promise { 'success' }
promise2 Promise {
<rejected> Error: error!!!
at promise.then (...)
at <anonymous> }
解释:promise 有 3 种状态:pending、fulfilled 或 rejected。状态改变只能是 pending->fulfilled 或者 pending->rejected,状态一旦改变则不能再变。promise2 是 promise1 返回的一个新的 Promise 实例。
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.then(console.log)
1
解释:.then 或者 .catch 的参数期望是函数,传入非函数则会发生值穿透。
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('once')
resolve('success')
}, 1000)
})
const start = Date.now()
promise.then((res) => {
console.log(res, Date.now() - start)
})
promise.then((res) => {
console.log(res, Date.now() - start)
})
once
success 1005
success 1007
解释:promise 的 .then 或者 .catch 可以被调用多次,但这里 Promise 构造函数只执行一次。或者说 promise 内部状态一经改变,并且有了一个值,那么后续每次调用 .then 或者 .catch 都会直接拿到该值。