Promise与宏微任务与异步处理
# 宏队列微队列
# 原理图
# 说明
JS
中用来存储待执行回调函数的队列包含2个不同特定的列队宏列队: 用来保存待执行的宏任务(回调), 比如: 定时器回调
DOM
事件回调ajax
回调微 列 队 : 用 来 保 存 待 执 行 的 微 任 务 ( 回 调 ), 比 如 :
promise
的 回 调MutationObserver
的回调JS
执行时会区别这 2 个队列JS
引擎首先必须先执行所有的初始化同步任务代码- 每次准备取出第一个宏任务执行前, 都要将所有的微任务一个一个取出 来执行
# Promise
Promise 是 JS 中进行异步编程的新的解决方案
- 从语法上来说: Promise 是一个构造函数
- 从功能上来说: promise 对象用来封装一个异步操作并可以获取其结果
# 概念
Promise
实例一共拥有三种状态:
pendding
:初始状态。resolve
:成功状态,返回一个成功的值。reject
: 失败状态,返回一个失败的原因。
一个 Promise
示例初始状态是 pendding
,并且只能修改一次状态。多次修改的话,只执行第一次,后面的不会响应。
Promise
执行流程:
为什么要使用 promise
指定回调函数的方式更加灵活
- 旧的: 必须在启动异步任务前指定
promise
启动异步任务 => 返回promie
对象 => 给promise
对象绑定回调函 数(甚至可以在异步任务结束后指定/多个)
支持链式调用, 可以解决回调地狱问题,终极解决方案 async 、await
# 属性方法
# Promise 构造函数
excutor
函数:执行器(resolve, reject) => {}
resolve
函数: 内部定义成功时我们调用的函数value => {}
reject
函数: 内部定义失败时我们调用的函数reason => {}
说明: excutor 会在 Promise 内部立即同步回调,异步操作在执行器中执行
# Promise.prototype.then
Promise.prototype.then (onResolved, onRejected) => {}
onResolved
函数: 成功的回调函数(value) => {}
onRejected
函数: 失败的回调函数(reason) => {}
说明: 指定用于得到成功 value 的成功回调和用于得到失败 reason 的失败回调 返回一个新的 promise 对象
# Promise.prototype.catch
Promise.prototype.catch(onRejected) => {}
onRejected
函数: 失败的回调函数(reason) => {}
说明: then()的语法糖, 相当于: then(undefined, onRejected)
# Promise.resolve
Promise.resolve(value) => {}
value
: 成功的数据或 promise
对象
说明: 返回一个成功/失败的 promise
对象
# Promise.reject
Promise.reject(reason) => {}
reason
: 失败的原因 说明: 返回一个失败的 promise
对象
# Promise.all
Promise.all(promises) => {}
promises
: 包含n
个promise
的数组
说明: 返回一个新的 promise
, 只有所有的 promise
都成功才成功, 只要有一个失败了就 直接失败
# Promise.race
Promise.race (promises) => {}
promises
: 包含 n
个 promise
的数组。
说明: 返回一个新的 promise
, 第一个完成的 promise
的结果状态就是最终的结果状态
# 关键问题
如何改变
promise
的状态?resolve(value)
: 如果当前是pendding
就会变为resolved
reject(reason)
: 如果当前是pendding
就会变为rejected
- 抛出异常: 如果当前是
pendding
就会变为rejected
一个
promise
指定多个成功/失败回调函数, 都会调用吗?- 当
promise
改变为对应状态时都会调用
- 当
改变
promise
状态和指定回调函数谁先谁后?
- 都有可能, 正常情况下是先指定回调再改变状态, 但也可以先改状态再指定回调
- 如何先改状态再指定回调?
- 在执行器中直接调用
resolve()/reject()
- 延迟更长时间才调用
then()
- 在执行器中直接调用
- 什么时候才能得到数据?
- 如果先指定的回调, 那当状态发生改变时, 回调函数就会调用, 得到数据
- 如果先改变的状态, 那当指定回调时, 回调函数就会调用, 得到数据
promise.then()
返回的新promise
的结果状态由什么决定?- 简单表达: 由 then()指定的回调函数执行的结果决定
- 详细表达
- 如果抛出异常, 新
promise
变为rejected
,reason
为抛出的异常 - 如果返回的是非
promise
的任意值, 新promise
变为resolved
,value
为返回的值 - 如果返回的是另一个新
promise
, 此promise
的结果就会成为新promise
的结果
- 如果抛出异常, 新
promise
如何串连多个操作任务?promise
的then()
返回一个新的promise
, 可以开成then()
的链式调用- 通过
then
的链式调用串连多个同步/异步任务
promise
异常传透?- 当使用
promise
的then
链式调用时, 可以在最后指定失败的回调 - 前面任何操作出了异常, 都会传到最后失败的回调中处理
- 当使用
- 中断
promise
链?- 当使用
promise
的then
链式调用时, 在中间中断, 不再调用后面的回调函数 - 办法: 在回调函数中返回一个
pendding
状态的promise
对象
- 当使用
# 手写 Promise
const PENDDING = "pendding";
const REJECTED = "rejected";
const RESOLVED = "resolved";
function resolve(value) {
if (this.state !== PENDDING) return;
this.state = RESOLVED;
this.data = value;
this.callbacks.forEach((callbacks) => {
setTimeout(() => {
callbacks.onResolved(value);
});
});
}
function reject(reason) {
if (this.state !== PENDDING) return;
this.state = REJECTED;
this.data = reason;
this.callbacks.forEach((callbacks) => {
setTimeout(() => {
callbacks.onRejected(reason);
});
});
}
class Promise {
constructor(excutor) {
this.state = PENDDING; // promise 状态
this.data = undefined; // 当前promise的数据
this.callbacks = []; // 用来存储回调函数的队列 形如 :[{onResolved,onRejected}]
try {
excutor(resolve.bind(this), reject.bind(this));
} catch (error) {
reject(error);
}
}
then(onResolved, onRejected) {
onResolved =
typeof onResolved === "function" ? onResolved : (value) => value;
onRejected =
typeof onRejected === "function" ? onRejected : (reason) => reason;
return new Promise((resolve, reject) => {
let handle = (handler) => {
try {
let res = handler(this.data);
if (res instanceof Promise) {
res.then(resolve, reject);
} else {
resolve(res);
}
} catch (error) {
reject(error);
}
};
if (this.state === RESOLVED) {
setTimeout(() => {
handle(onResolved);
});
} else if (this.state === REJECTED) {
setTimeout(() => {
handle(onRejected);
});
} else {
this.callbacks.push({
onResolved(value) {
handle(onResolved);
},
onRejected(reason) {
handle(onRejected);
},
});
}
});
}
catch(onRejected) {
return this.then(undefined, onRejected);
}
static resolve(value) {
return new Promise((resolve, reject) => {
if (value instanceof Promise) {
value.then(resolve, reject);
} else {
resolve(value);
}
});
}
static reject(reason) {
return new Promise((resolve, reject) => {
if (reason instanceof Promise) {
reason.then(reject, reject);
} else {
reject(reason);
}
});
}
static all(promises) {
return new Promise((reslove, reject) => {
let count = 0;
let resArr = [];
promises.forEach((p, index) => {
Promise.resolve(p).then(
(value) => {
count++;
resArr[index] = value;
if (count === promises.length) {
reslove(resArr);
}
},
(reason) => {
reject(reason);
}
);
});
});
}
static race(promises) {
return new Promise((resovle, reject) => {
promises.forEach((p) => {
Promise.resolve(p).then(resovle, reject);
});
});
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# async / await
# async
- 函数的返回值为
promise
对象 promise
对象的结果由async
函数执行的返回值决定
# await
await
右侧的表达式一般为promise
对象, 但也可以是其它的值- 如果表达式是
promise
对象,await
返回的是promise
成功的值 - 如果表达式是其它值, 直接将此值作为
await
的返回值
# 注意
await
必须写在async
函数中, 但async
函数中可以没有await
- 如果
await
的promise
失败了, 就会抛出异常, 需要通过try...catch
捕获处理 await
表达式 :是微任务,await
后面的代码表达式以及后面的代码都会在执行微任务时执行。是异步的。
# 宏任务、微任务题
# 题一
setTimeout(()=>{
console.log(1)
},0)
Promise.resolve().then(()=>{
console.log(2)
})
Promise.resolve().then(()=>{
console.log(4)
})
console.log(3)
2
3
4
5
6
7
8
9
10
# 题二
setTimeout(() => {
console.log(1)
}, 0)
new Promise((resolve) => {
console.log(2)
resolve()
}).then(() => {
console.log(3)
}).then(() => {
console.log(4)
})
console.log(5)
2
3
4
5
6
7
8
9
10
11
12
# 题三
const first = () => (new Promise((resolve, reject) => {
console.log(3)
let p = new Promise((resolve, reject) => {
console.log(7)
setTimeout(() => {
console.log(5)
resolve(6)
}, 0)
resolve(1)
})
resolve(2)
p.then((arg) => {
console.log(arg)
})
}))
first().then((arg) => {
console.log(arg)
})
console.log(4)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 题四
setTimeout(() => {
console.log("0")
}, 0)
new Promise((resolve,reject)=>{
console.log("1")
resolve()
}).then(()=>{
console.log("2")
new Promise((resolve,reject)=>{
console.log("3")
resolve()
}).then(()=>{
console.log("4")
}).then(()=>{
console.log("5")
})
}).then(()=>{
console.log("6")
})
new Promise((resolve,reject)=>{
console.log("7")
resolve()
}).then(()=>{
console.log("8")
})
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25