一、准备
1.1 区别实例对象与函数对象
- 实例对象:new 函数产生的对象,称为实例对象,简称为对象
- 函数对象:将函数作为对象使用时,称为函数对象
1 2 3 4 5 6 7 8 9
| function Fn() { } const fn = new Fn()
console.log(Fn.prototype) Fn.bind({}) $('#test') $.get('/test')
|
()的左边必然是函数,点的左边必然是对象
1.2 回调函数
同步回调
定义:立即执行,完全执行完了才结束,不会放入回调队列中
举例:数组遍历相关的回调 / Promise 的 excutor 函数
1 2 3 4 5 6 7 8 9 10
| const arr = [1, 3, 5] arr.forEach(item => { console.log(item) }) console.log('forEach()之后')
|
异步回调
定义:不会立即执行,会放入回调队列中将来执行
举例:定时器回调 / ajax 回调 / Promise 成功或失败的回调
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| setTimeout(() => { console.log('timeout callback()') }, 0) console.log('setTimeout()之后')
new Promise((resolve, reject) => { resolve(1) }).then( value => { console.log('value', value) }, reason => { console.log('reason', reason) } ) console.log('----')
|
js 引擎是先把初始化的同步代码都执行完成后,才执行回调队列中的代码
1.3 JS 的 error 处理
错误的类型
Error:所有错误的父类型
ReferenceError:引用的变量不存在
TypeError:数据类型不正确
1 2 3 4 5 6
| let b console.log(b.xxx)
let b = {} b.xxx()
|
RangeError:数据值不在其所允许的范围内
1 2 3 4 5
| function fn() { fn() } fn()
|
SyntaxError:语法错误
错误处理
捕获错误:try … catch
抛出错误:throw error
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function something() { if (Date.now() % 2 === 1) { console.log('当前时间为奇数,可以执行任务') } else { throw new Error('当前时间为偶数,无法执行任务') } }
try { something() } catch (error) { alert(error.message) }
|
错误对象
massage 属性:错误相关信息
stack 属性:函数调用栈记录信息
1 2 3 4 5 6 7 8 9 10 11
| try { let d console.log(d.xxx) } catch (error) { console.log(error.message) console.log(error.stack) } console.log('出错之后')
|
因为错误被捕获处理了,后面的代码才能运行下去,打印出‘出错之后’
二、Promise 的理解和使用
2.1 Promise 是什么
2.1.1 Promise 的理解
抽象表达:Promise 是 JS 中进行异步编程的新的解决方案
具体表达:
- 语法上:Promise 是一个构造函数
- 功能上:Promise 对象用来封装一个异步操作并可以获取其结果
2.1.2 Promise 的状态改变
- pending 变为 resolved
- pending 变为 rejected
只有这两种,且一个 promise 对象只能改变一次。无论成功还是失败,都会有一个结果数据。成功的结果数据一般称为 value,而失败的一般称为 reason。
2.1.3 Promise 的基本流程

2.1.4 Promise 的基本使用
1 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
| const p = new Promise((resolve, reject) => { setTimeout(() => { const time = Date.now() if (time % 2 == 0) { resolve('成功的数据,time=' + time) } else { reject('失败的数据,time=' + time) } }, 1000) })
p.then( value => { console.log('成功的回调', value) }, reason => { console.log('失败的回调', reason) } )
|
.then() 和执行器(excutor)同步执行,.then() 中的回调函数异步执行
2.2 为什么要用 Promise
1.指定回调函数的方式更加灵活
旧的:必须在启动异步任务前指定
promise:启动异步任务 => 返回 promise 对象 => 给 promise 对象绑定回调函数(甚至可以在异步任务结束后指定)
2.支持链式调用,可以解决回调地狱问题
什么是回调地狱?
回调函数嵌套调用,外部回调函数异步执行的结果是其内部嵌套的回调函数执行的条件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| doSomething(function (result) { doSomethingElse( result, function (newResult) { doThirdThing( newResult, function (finalResult) { console.log('Got the final result:' + finalResult) }, failureCallback ) }, failureCallback ) }, failureCallback)
|
回调地狱的缺点?
不便于阅读 / 不便于异常处理
解决方案?
promise 链式调用
终极解决方案?
async/await
使用 promise 的链式调用解决回调地狱
1 2 3 4 5 6 7
| doSomething() .then(result => doSomethingElse(result)) .then(newResult => doThirdThing(newResult)) .then(finalResult => { console.log('Got the final result:' + finalResult) }) .catch(failureCallback)
|
回调地狱的终极解决方案 async/await
1 2 3 4 5 6 7 8 9 10
| async function request() { try { const result = await doSomething() const newResult = await doSomethingElse(result) const finalResult = await doThirdThing(newResult) console.log('Got the final result:' + finalResult) } catch (error) { failureCallback(error) } }
|
2.3 如何使用 Promise
API
Promise 构造函数:Promise(excutor) {}
excutor 函数:同步执行 (resolve, reject) => {}
resolve 函数:内部定义成功时调用的函数 resove(value)
reject 函数:内部定义失败时调用的函数 reject(reason)
说明:excutor 是执行器,会在 Promise 内部立即同步回调,异步操作 resolve/reject
就在 excutor 中执行
Promise.prototype.then 方法:p.then(onResolved, onRejected)
1)onResolved 函数:成功的回调函数 (value) => {}
2)onRejected 函数:失败的回调函数 (reason) => {}
说明:指定用于得到成功 value 的成功回调和用于得到失败 reason 的失败回调,返回一个新的 promise 对象
Promise.prototype.catch 方法:p.catch(onRejected)
1)onRejected 函数:失败的回调函数 (reason) => {}
说明:then() 的语法糖,相当于 then(undefined, onRejected)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| new Promise((resolve, reject) => { setTimeout(() => { if(...) { resolve('成功的数据') } else { reject('失败的数据') } }, 1000) }).then( value => { console.log(value) } ).catch( reason => { console.log(reason) } )
|
Promise.resolve 方法:Promise.resolve(value)
value:将被 Promise
对象解析的参数,也可以是一个成功或失败的 Promise
对象
返回:返回一个带着给定值解析过的 Promise
对象,如果参数本身就是一个 Promise
对象,则直接返回这个 Promise
对象。
Promise.reject 方法:Promise.resolve(reason)
reason:失败的原因
说明:返回一个失败的 promise 对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| new Promise((resolve, reject) => { resolve(1) })
const p1 = Promise.resolve(1) const p2 = Promise.resolve(2) const p3 = Promise.reject(3)
p1.then(value => { console.log(value) }) p2.then(value => { console.log(value) }) p3.catch(reason => { console.log(reason) })
|
Promise.resolve()/Promise.reject()
方法就是一个语法糖
Promise.all 方法:Promise.all(iterable)
iterable:包含 n 个 promise 的可迭代对象,如 Array
或 String
说明:返回一个新的 promise,只有所有的 promise 都成功才成功,只要有一个失败了就直接失败
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const pAll = Promise.all([p1, p2, p3]) const pAll2 = Promise.all([p1, p2])
pAll.then( value => { console.log('all onResolved()', value) }, reason => { console.log('all onRejected()', reason) } )
pAll2.then( values => { console.log('all onResolved()', values) }, reason => { console.log('all onRejected()', reason) } )
|
Promise.race 方法:Promise.race(iterable)
iterable:包含 n 个 promise 的可迭代对象,如 Array
或 String
说明:返回一个新的 promise,第一个完成的 promise 的结果状态就是最终的结果状态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const pRace = Promise.race([p1, p2, p3])
const p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve(1) }, 1000) }) const p2 = Promise.resolve(2) const p3 = Promise.reject(3)
pRace.then( value => { console.log('race onResolved()', value) }, reason => { console.log('race onRejected()', reason) } )
|
Promise 的几个关键问题
1.如何改变 promise 的状态?
(1)resolve(value):如果当前是 pending 就会变为 resolved
(2)reject(reason):如果当前是 pending 就会变为 rejected
(3)抛出异常:如果当前是 pending 就会变为 rejected
1 2 3 4 5 6 7 8 9 10 11 12
| const p = new Promise((resolve, reject) => { throw new Error('出错了') }) p.then( value => {}, reason => { console.log('reason', reason) } )
|
2.一个 promise 指定多个成功/失败回调函数,都会调用吗?
当 promise 改变为对应状态时都会调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const p = new Promise((resolve, reject) => { reject(2) }) p.then( value => {}, reason => { console.log('reason', reason) } ) p.then( value => {}, reason => { console.log('reason2', reason) } )
|
3.改变 promise 状态和指定回调函数谁先谁后?
都有可能,常规是先指定回调再改变状态,但也可以先改状态再指定回调
如何先改状态再指定回调?
(1)在执行器中直接调用 resolve()/reject()
(2)延迟更长时间才调用 then()
什么时候才能得到数据?
(1)如果先指定的回调,那当状态发生改变时,回调函数就会调用得到数据
(2)如果先改变的状态,那当指定回调时,回调函数就会调用得到数据
1 2 3 4 5 6 7 8 9
| new Promise((resolve, reject) => { setTimeout(() => { resolve(1) }, 1000) }).then( value => {}, reason => {} )
|
此时,先指定回调函数,保存当前指定的回调函数;后改变状态(同时指定数据),然后异步执行之前保存的回调函数。
1 2 3 4 5 6 7
| new Promise((resolve, reject) => { resolve(1) }).then( value => {}, reason => {} )
|
这种写法,先改变的状态(同时指定数据),后指定回调函数(不需要再保存),直接异步执行回调函数
4.promise.then() 返回的新 promise 的结果状态由什么决定?
(1)简单表达:由 then() 指定的回调函数执行的结果决定
(2)详细表达:
① 如果抛出异常,新 promise 变为 rejected,reason 为抛出的异常
② 如果返回的是非 promise 的任意值,新 promise 变为 resolved,value 为返回的值
③ 如果返回的是另一个新 promise,此 promise 的结果就会成为新 promise 的结果
1 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
| new Promise((resolve, reject) => { resolve(1) }) .then( value => { console.log('onResolved1()', value) }, reason => { console.log('onRejected1()', reason) } ) .then( value => { console.log('onResolved2()', value) }, reason => { console.log('onRejected2()', reason) } )
new Promise((resolve, reject) => { resolve(1) }) .then( value => { console.log('onResolved1()', value) }, reason => { console.log('onRejected1()', reason) } ) .then( value => { console.log('onResolved2()', value) }, reason => { console.log('onRejected2()', reason) } )
|
5.promise 如何串联多个操作任务?
(1)promise 的 then() 返回一个新的 promise,可以并成 then() 的链式调用
(2)通过 then 的链式调用串联多个同步/异步任务
1 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
| new Promise((resolve, reject) => { setTimeout(() => { console.log('执行任务1(异步)') resolve(1) }, 1000) }) .then(value => { console.log('任务1的结果', value) console.log('执行任务2(同步)') return 2 }) .then(value => { console.log('任务2的结果', value) return new Promise((resolve, reject) => { setTimeout(() => { console.log('执行任务3(异步)') resolve(3) }, 1000) }) }) .then(value => { console.log('任务3的结果', value) })
|
6.Promise 异常穿透(传透)?
(1)当使用 promise 的 then 链式调用时,可以在最后指定失败的回调
(2)前面任何操作出了异常,都会传到最后失败的回调中处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| new Promise((resolve, reject) => { reject(1) }) .then(value => { console.log('onResolved1()', value) return 2 }) .then(value => { console.log('onResolved2()', value) return 3 }) .then(value => { console.log('onResolved3()', value) }) .catch(reason => { console.log('onRejected1()', reason) })
|
相当于这种写法:
1 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
| new Promise((resolve, reject) => { reject(1) }) .then( value => { console.log('onResolved1()', value) return 2 }, reason => { throw reason } ) .then( value => { console.log('onResolved2()', value) return 3 }, reason => { throw reason } ) .then( value => { console.log('onResolved3()', value) }, reason => { throw reason } ) .catch(reason => { console.log('onRejected1()', reason) })
|
所以失败的结果是一层一层处理下来的,最后传递到 catch 中。
或者,将 reason => {throw reason}
替换为 reason => Promise.reject(reason)
也是一样的
7.中断 promise 链?
当使用 promise 的 then 链式调用时,在中间中断,不再调用后面的回调函数
办法:在回调函数中返回一个 pending 状态的 promise 对象
1 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
| new Promise((resolve, reject) => { reject(1) }) .then(value => { console.log('onResolved1()', value) return 2 }) .then(value => { console.log('onResolved2()', value) return 3 }) .then(value => { console.log('onResolved3()', value) }) .catch(reason => { console.log('onRejected1()', reason) }) .then( value => { console.log('onResolved4()', value) }, reason => { console.log('onRejected2()', reason) } )
|
为了在 catch 中就中断执行,可以这样写:
1 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
| new Promise((resolve, reject) => { reject(1) }) .then(value => { console.log('onResolved1()', value) return 2 }) .then(value => { console.log('onResolved2()', value) return 3 }) .then(value => { console.log('onResolved3()', value) }) .catch(reason => { console.log('onRejected1()', reason) return new Promise(() => {}) }) .then( value => { console.log('onResolved4()', value) }, reason => { console.log('onRejected2()', reason) } )
|
在 catch 中返回一个新的 promise,且这个 promise 没有结果。
由于,返回的新的 promise 结果决定了后面 then 中的结果,所以后面的 then 中也没有结果。
这就实现了中断 promise 链的效果。
三、自定义(手写)Promise
3.1 Promise.js
Promise.js 是 ES5 function 实现 Promise 的完整版
1 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
|
;(function (window) { const PENDING = 'pending' const RESOLVED = 'resolved' const REJECTED = 'rejected'
function Promise(excutor) { const self = this self.status = PENDING self.data = undefined self.callbacks = [] function resolve(value) { if (self.status !== PENDING) { return } self.status = RESOLVED self.data = value if (self.callbacks.length > 0) { setTimeout(() => { self.callbacks.forEach(callbacksObj => { callbacksObj.onResolved(value) }) }) } }
function reject(reason) { if (self.status !== PENDING) { return } self.status = REJECTED self.data = reason if (self.callbacks.length > 0) { setTimeout(() => { self.callbacks.forEach(callbacksObj => { callbacksObj.onRejected(reason) }) }) } } try { excutor(resolve, reject) } catch (error) { reject(error) } }
Promise.prototype.then = function (onResolved, onRejected) { onResolved = typeof onResolved === 'function' ? onResolved : value => value onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason } const self = this return new Promise((resolve, reject) => {
function handle(callback) {
try { const result = callback(self.data) if (result instanceof Promise) { result.then( value => resolve(value), reason => reject(reason) ) } else { resolve(result) } } catch (error) { reject(error) } } if (self.status === PENDING) { self.callbacks.push({ onResolved(value) { handle(onResolved) }, onRejected(reason) { handle(onRejected) }, }) } else if (self.status === RESOLVED) { setTimeout(() => { handle(onResolved) }) } else { setTimeout(() => { handle(onRejected) }) } }) }
Promise.prototype.catch = function (onRejected) { return this.then(undefined, onRejected) }
Promise.resolve = function (value) { return new Promise((resolve, reject) => { if (value instanceof Promise) { value.then(resolve, reject) } else { resolve(value) } }) }
Promise.reject = function (reason) { return new Promise((resolve, reject) => { reject(reason) }) }
Promise.all = function (promises) { let resolvedCount = 0 const values = new Array(promises.length) return new Promise((resolve, reject) => { promises.forEach((p, index) => { Promise.resolve(p).then( value => { resolvedCount++ values[index] = value if (resolvedCount === promises.length) { resolve(values) } }, reason => { reject(reason) } ) }) }) }
Promise.race = function (promises) { return new Promise((resolve, reject) => { promises.forEach((p, index) => { Promise.resolve(p).then( value => { resolve(value) }, reason => { reject(reason) } ) }) }) }
Promise.resolveDelay = function (value, time) { return new Promise((resolve, reject) => { setTimeout(() => { if (value instanceof Promise) { value.then(resolve, reject) } else { resolve(value) } }, time) }) }
Promise.rejectDelay = function (reason, time) { return new Promise((resolve, reject) => { setTimeout(() => { reject(reason) }, time) }) }
window.Promise = Promise })(window)
|
3.2 Promise_class.js
Promise_class.js 是 ES6 class 实现 Promise 的完整版
1 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
|
;(function (window) { const PENDING = 'pending' const RESOLVED = 'resolved' const REJECTED = 'rejected'
class Promise {
constructor(excutor) { const self = this self.status = PENDING self.data = undefined self.callbacks = [] function resolve(value) { if (self.status !== PENDING) { return } self.status = RESOLVED self.data = value if (self.callbacks.length > 0) { setTimeout(() => { self.callbacks.forEach(callbacksObj => { callbacksObj.onResolved(value) }) }) } }
function reject(reason) { if (self.status !== PENDING) { return } self.status = REJECTED self.data = reason if (self.callbacks.length > 0) { setTimeout(() => { self.callbacks.forEach(callbacksObj => { callbacksObj.onRejected(reason) }) }) } }
try { excutor(resolve, reject) } catch (error) { reject(error) } }
then(onResolved, onRejected) { onResolved = typeof onResolved === 'function' ? onResolved : value => value onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason } const self = this return new Promise((resolve, reject) => {
function handle(callback) {
try { const result = callback(self.data) if (result instanceof Promise) { result.then( value => resolve(value), reason => reject(reason) ) } else { resolve(result) } } catch (error) { reject(error) } } if (self.status === PENDING) { self.callbacks.push({ onResolved(value) { handle(onResolved) }, onRejected(reason) { handle(onRejected) }, }) } else if (self.status === RESOLVED) { setTimeout(() => { handle(onResolved) }) } else { setTimeout(() => { handle(onRejected) }) } }) }
catch(onRejected) { return this.then(undefined, onRejected) }
static resolve = function (value) { return new Promise((resolve, reject) => { if (value instanceof Promise) { value.then(resolve, reject) } else { resolve(value) } }) }
static reject = function (reason) { return new Promise((resolve, reject) => { reject(reason) }) }
static all = function (promises) { let resolvedCount = 0 const values = new Array(promises.length) return new Promise((resolve, reject) => { promises.forEach((p, index) => { Promise.resolve(p).then( value => { resolvedCount++ values[index] = value if (resolvedCount === promises.length) { resolve(values) } }, reason => { reject(reason) } ) }) }) }
static race = function (promises) { return new Promise((resolve, reject) => { promises.forEach((p, index) => { Promise.resolve(p).then( value => { resolve(value) }, reason => { reject(reason) } ) }) }) }
static resolveDelay = function (value, time) { return new Promise((resolve, reject) => { setTimeout(() => { if (value instanceof Promise) { value.then(resolve, reject) } else { resolve(value) } }, time) }) }
static rejectDelay = function (reason, time) { return new Promise((resolve, reject) => { setTimeout(() => { reject(reason) }, time) }) } }
window.Promise = Promise })(window)
|
3.3 then.js
then.js 是第二次重写的 then()方法
1 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
|
Promise.prototype.then = function (onResolved, onRejected) { const self = this onResolved = typeof onResolved === 'function' ? onResolved : value => value onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason } return new Promise((resolve, reject) => {
function handle(callback) {
try { const result = callback(self.data) if (result instanceof Promise) { result.then(resolve.reject) } else { resolve(result) } } catch (error) { reject(error) } } if (self.status === RESOLVED) { setTimeout(() => { handle(onResolved) }) } else if (self.status === REJECTED) { setTimeout(() => { handle(onRejected) }) } else { self.callbacks.push({ onResolved(value) { handle(onResolved) }, onRejected(reason) { handle(onRejected) }, }) } }) }
|
3.4 Promise.html
自定义 Promise.html 文件用来测试
1 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 133 134
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head>
<body> <script src="Promise_class.js"></script>
<script>
const p1 = Promise.resolve(2) const p2 = Promise.resolve(Promise.resolve(3)) const p3 = Promise.resolve(Promise.reject(4))
const p4 = Promise.resolveDelay(5, 1000) const p5 = Promise.reject(6) const pAll = Promise.all([p4, 7, p1, p2]) pAll.then( value => { console.log('all onResolved()', value) }, reason => { console.log('all onRejected()', reason) } )
const p6 = Promise.resolveDelay(66, 2000) const p7 = Promise.rejectDelay(77, 3000) p6.then(value => { console.log('p6', value) }) p7.catch(reason => { console.log('p7', reason) }) </script> </body> </html>
|
四、async 与 await
4.1 async 函数
- 函数的返回值为 promise 对象
- promise 对象的结果由 async 函数执行的返回值决定
1 2 3 4 5 6 7 8
| async function fn1() { throw 2 } const result = fn1() console.log(result)
|
这时,可以将 result.then():
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| async function fn1() { throw 2 } const result = fn1() result.then( value => { console.log('onResolved()', value) }, reason => { console.log('onRejected()', reason) } )
|
也可以在异步函数中返回一个 promise
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| async function fn1() { return Promise.resolve(3) } const result = fn1() result.then( value => { console.log('onResolved()', value) }, reason => { console.log('onRejected()', reason) } )
|
也就是说,一旦在函数前加 async,它返回的值都将被包裹在 Promise 中,这个 Promise 的结果由函数执行的结果决定。
上面的栗子都是立即成功/失败的 promise,也可以返回延迟成功/失败的 promise:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| async function fn1() { return new Promise((resolve, reject) => { setTimeout(() => { resolve(4) }, 1000) }) } const result = fn1() result.then( value => { console.log('onResolved()', value) }, reason => { console.log('onRejected()', reason) } )
|
4.2 await 表达式
MDN
async
await
语法
[return_value] = await expression;
表达式
一个 Promise
对象或者任何要等待的值
。
返回值
返回 Promise 对象的处理结果。如果等待的不是 Promise 对象,则返回该值本身。
解释
await 表达式会暂停当前 async function 的执行,等待 Promise 处理完成。
- await 右侧的表达式一般为 promise 对象,但也可以是其他的值
- 如果表达式是 promise 对象,await 返回的是 promise 成功的值
- 如果表达式是其他值,直接将此值作为 await 的返回值
注意:
await 必须写在 async 函数中,但 async 函数中可以没有 await
如果 await 的 promise 失败了,就会抛出异常,需要通过 try…catch 来捕获处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| function fn2() { return new Promise((resolve, reject) => { setTimeout(() => { resolve(5) }, 1000) }) }
function fn4() { return 6 }
async function fn3() { const value = await fn2() console.log('value', value) } fn3()
|
不写 await,只能得到一个 promise 对象。在表达式前面加上 await,1s 后将得到 promise 的结果 5,但是要用 await 必须在函数上声明 async。
await 右侧表达式 fn2() 为 promise,得到的结果就是 promise 成功的 value;await 右侧表达式 fn4() 不是 promise,得到的结果就是这个值本身。
Promise 对象的结果也有可能失败:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function fn2() { return new Promise((resolve, reject) => { setTimeout(() => { reject(5) }, 1000) }) }
async function fn3() { const value = await fn2() console.log('value', value) } fn3()
|
await 只能得到成功的结果,要想得到失败的结果就要用 try/catch:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function fn2() { return new Promise((resolve, reject) => { setTimeout(() => { reject(5) }, 1000) }) }
async function fn3() { try { const value = await fn2() console.log('value', value) } catch (error) { console.log('得到失败的结果', error) } } fn3()
|
下面这个栗子中,fn1 是第 2 种情况,fn2 是第 3 种情况,fn3 也是第 3 种情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| async function fn1() { return 1 } function fn2() { return 2 } function fn3() { throw 3 } async function fn3() { try { const value = await fn1() console.log('value', value) } catch (error) { console.log('得到失败的结果', error) } } fn3()
|
五、JS 异步之宏队列与微队列

JS 中用来存储待执行回调函数的队列包含 2 个不同特定的队列
宏队列:用来保存待执行的宏任务(回调),比如:定时器回调/DOM 事件回调/ajax 回调
微队列:用来保存待执行的微任务(回调),比如:promise 的回调/MutationObserver 的回调
JS 执行时会区别这 2 个队列
(1) JS 引擎首先必须执行所有的初始化同步任务代码
(2) 每次准备取出第一个宏任务前,都要将所有的微任务一个一个取出来执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| setTimeout(() => { console.log('timeout callback1()') }, 0) setTimeout(() => { console.log('timeout callback2()') }, 0) Promise.resolve(1).then(value => { console.log('Promise onResolved1()', value) }) Promise.resolve(1).then(value => { console.log('Promise onResolved2()', value) })
|
先执行所有的同步代码,再执行队列代码。队列代码中,微队列中的回调函数优先执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| setTimeout(() => { console.log('timeout callback1()') Promise.resolve(1).then( value => { console.log('Promise onResolved3()', value) } }, 0) setTimeout(() => { console.log('timeout callback2()') }, 0) Promise.resolve(1).then( value => { console.log('Promise onResolved1()', value) } ) Promise.resolve(1).then( value => { console.log('Promise onResolved2()', value) } )
|
执行完 timeout callback1()
后 Promise onResolved3()
会立即被放入微队列。在执行 timeout callback2()
前,Promise onResolved3()
已经在微队列中了,所以先执行 Promise onResolved3()
。
六、相关面试题
6.1 面试题 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| setTimeout(() => { console.log(1) }, 0) new Promise(resolve => { console.log(2) resolve() }) .then(() => { console.log(3) }) .then(() => { console.log(4) }) console.log(5)
|
2 是 excutor 执行器,是同步回调函数,所以在同步代码中。.then() 中的函数才是异步回调
其中,执行完 2 后改变状态为 resolve,第一个 .then() 中的 3 会放入微队列,但还没执行(promise 是 pending 状态),就不会把结果给第二个 then(),这时,4 就会缓存起来但不会被放入微队列。只有在微队列中的 3 执行完后才把 4 放入微队列。
所以顺序是:
1 放入宏队列,2 执行,3 放入微队列,4 缓存起来等待 Promise 的状态改变,5 执行,微队列中的 3 执行,4 放入微队列,微队列中的 4 执行,宏队列中的 1 执行。
6.2 面试题 2
1 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
| 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)
|
6.3 面试题 3
1 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
| 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') })
|
顺序:
0 放入宏队列,同步执行 1,2 放入微队列,6 缓存到内部,同步执行 7,8 放入微队列,取出微队列中的 2 执行,同步执行 3,4 放入微队列,5 缓存到内部,6 放入微队列(因为 6 的前一个 promise 已经执行完了返回成功结果 undefined),取出微队列中的 8 执行,取出微队列中的 4 执行,5 放入微队列,取出微队列中的 6 执行,取出微队列中的 5 执行,取出宏队列中的 0 执行