promise 易混淆、易错
1 | const promise = new Promise((resolve, reject) => { |
多个 .catch
都是最初的实例1
2
3
4
5var p = new Promise((resolve, reject) => {
reject(Error('The Fails!'))
})
p.catch(error => console.log(error.message))
p.catch(error => console.log(error.message))
宏、微任务
1 | const first = () => (new Promise((resolve, reject) => { |
promise 成功失败、相互转换
1 | let p1 = new Promise((resolve, reject) => { |
promise catch
捕获前一级的 onRejected1
2
3
4
5
6
7
8
9
10
11
12
13
14
15/**
catch相当于
.then(null,err=>{})
*/
Promise.resolve(1)
.then((res) => {
console.log(res);
return 2;
})
.catch((err) => {
return 3;
})
.then((res) => {
console.log(res);
});
promise-穿透
- 当then里onFulfiled和onRejected不是函数时会发生穿透。
- onFulfiled、onRejected不是函数时有默认值
1
2
3
4
5
6onFulfiled = (value)=>value;
onRejected = (err)=throw err;
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.then(console.log(1))
执行顺序
macroTask=>microTask[多个执行结束]=>macroTask[执行一个]=>microTask[多个执行结束]1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20setTimeout(() => {
console.log('setTimeout')
})
let p1 = new Promise((resolve) => {
console.log('Promise1')
resolve('Promise2')
})
p1.then((res) => {
console.log(res)
})
console.log(1)
// 宏任务 [timeout1]
// 微任务 [pormise1]
/**
* promise1
* 1
* promise2
* settimeout
*/