- 代码臃肿,可读性差。
- 代码耦合度高,可维护性差,难以复用
- 回调函数都是匿名函数,不方便调试
状态一旦改变就不能再做更改了。
Promise在创建后会立即调用,然后等待执行resolve()函数或者reject()函数来确定Promise最终状态。在上一轮then()函数内部return的值会作为下一轮函数接收的参数值。
then()函数中不能返回Promise()实例本身,否则会出现Promise()循环引用的问题,抛出异常。
处理rejected状态的Promise的回调函数最好用catch()来做
catch()就是为了错误而存在的。rejectconst p = Promise.all([p1, p2, p3]);
p的状态由p1,p2,p3三个值共同决定,只有当三者全部都为fulfilled成功状态的时候,p的状态才会变成fulfilled状态,此时p1,p2,p3的值组成一个数组,作为p的then()函数的回调函数的参数。
只要有一个是rejected,p的状态就变为rejected,此时第一个被reject的实例的返回值会作为p的catch()函数的回调函数的参数。
const p1 = new Promise((resolve, reject) => {
resolve('success');
})
.then(result => result)
.catch(e => e);
const p2 = new Promise((resolve, reject) => {
throw new Error('error');
})
.then(result => result)
.catch(e => e);
Promise.all([p1, p2])
.then(result => console.log(result)) // ['success', Error: error]
.catch(e => console.log(e));
此时p2的状态是
fulfilled,p1的状态也是fulfilled,所以出现的值是['success', Error: error]
const p = Promise.race([p1, p2, p3])
只要其中有一个状态出现了变化,那就直接进行监听。
const p1 = axios.get('/testUrl');
const p2 = new Promise((resolve, reject) => {
setTimeout(() => throw new Error('test'), 5000)
})
const p = Promise.race([p1, p2])
p.then(console.log).catch(console.error)
Promise.resolve('success'); == new Promise(resolve => resolve('promise'))
Promise.reject('reject'); == new Promise(reject => reject('reject'))
const promise = new Promise((resolve, reject) => {
console.log(1);
resolve();
console.log(2);
});
promise.then(() => {
console.log(3);
});
console.log(4);
const promise3 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('once');
resolve('success');
}, 1000)
});
const start = Date.now()
promise3.then((res) => {
console.log(res, Date.now() - start)
})
promise3.then((res) => {
console.log(res, Date.now() - start)
})
/*
once
success 1021
success 1022
*/
Promise.resolve()
.then(() => {
console.log(1);
return new Error('error!!!');
})
.then((res) => {
console.log(2);
console.log('then: ', res);
})
.catch((err) => {
console.log(3);
console.log('catch: ', err);
});
/*
1
2
then: Error: error!!!
*/
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.then(console.log);
// 1
值穿透 ==> 传递的值会被直接忽略掉,继续执行链式调用后续的函数。
Promise.resolve()
.then(function success (res) {
throw new Error('error');
}, function fail1 (e) {
console.error('fail1: ', e);
})
.catch(function fail2 (e) {
console.error('fail2: ', e);
});
then()函数的第二个函数不能捕获第一个函数中抛出的异常,而catch()函数却能捕获到第一个函数中抛出的异常。