前奏
1.函数对象
/*
1. 函数对象与实例对象
函数对象: 将函数作为对象使用时, 简称为函数对象
实例对象: new 函数产生的对象, 简称为对象
*/
function Fn() {
// Fn函数
}
const fn = new Fn() // Fn是构造函数 fn是实例对象(简称为对象)
console.log(Fn.prototype) // Fn是函数对象
Fn.call({
}) // Fn是函数对象
$('#test') // jQuery函数
$.get('/test') // jQuery函数对象
function Person(params) {
}
PS:Fn() 中的Fn为函数,Fn.b中的Fn为对象,只有Fn为函数对象才有bind,apply等方法
原型对象(有点像类)方法,其实例对象可以调用
函数对象调用方法,有点像类调用静态方法
2.回调函数
特点:①自己定义 ②非自己直接调用 ③但执行了
PS:若参数是回调函数,具体得看调用时传的的啥函数
/*
1). 同步回调:
理解: 立即执行, 完全执行完了才结束, 不会放入回调队列中
例子: 数组遍历相关的回调函数 / Promise的excutor函数
2). 异步回调:
理解: 不会立即执行, 会放入回调队列中将来执行
例子: 定时器回调 / ajax回调 / Promise的成功|失败的回调
*/
// 1. 同步回调函数
// const arr = [1, 3, 5]
arr.forEach(item => {
// 遍历回调, 同步回调函数, 不会放入列队, 一上来就要执行完
console.log(item)
})
console.log('forEach()之后')
// 2. 异步回调函数
setTimeout(() => {
// 异步回调函数, 会放入队列中将来执行
console.log('timout callback()')
}, 0)
console.log('setTimeout()之后')
3.Error
1. 错误的类型
Error: 所有错误的父类型
ReferenceError: 引用的变量不存在
TypeError: 数据类型不正确的错误
RangeError: 数据值不在其所允许的范围内
SyntaxError: 语法错误
2. 错误处理
捕获错误: try ... catch
抛出错误: throw error对象
3. 错误对象
message属性: 错误相关信息
stack属性: 函数调用栈记录信息
正题
1.基本使用
/*
1. Promise构造函数: Promise (excutor) {}
excutor函数: 同步执行 (resolve, reject) => {}
resolve函数: 内部定义成功时我们调用的函数 value => {}
reject函数: 内部定义失败时我们调用的函数 reason => {}
说明: excutor会在Promise内部立即同步回调,异步操作在执行器中执行
2. Promise.prototype.then方法: (onResolved, onRejected) => {}
onResolved函数: 成功的回调函数 (value) => {}
onRejected函数: 失败的回调函数 (reason) => {}
说明: 指定用于得到成功value的成功回调和用于得到失败reason的失败回调
返回一个新的promise对象
3. Promise.prototype.catch方法: (onRejected) => {}
onRejected函数: 失败的回调函数 (reason) => {}
说明: then()的语法糖, 相当于: then(undefined, onRejected)
4. Promise.resolve方法: (value) => {}
value: 成功的数据或promise对象
说明: 返回一个成功/失败的promise对象
5. Promise.reject方法: (reason) => {}
reason: 失败的原因
说明: 返回一个失败的promise对象
6. Promise.all方法: (promises) => {}
promises: 包含n个promise的数组
说明: 返回一个新的promise, 只有所有的promise都成功才成功, 只要有一个失败了就直接失败
7. Promise.race方法: (promises) => {}
promises: 包含n个promise的数组
说明: 返回一个新的promise, 第一个完成的promise的结果状态就是最终的结果状态
*/
// 1. 创建一个新的promise对象
const p = new Promise((resolve, reject) => {
// 执行器函数 同步回调
console.log('执行 excutor')
// 2. 可执行同步/异步任务
// 3.1. 如果成功了, 调用resolve(value)
// 3.2. 如果失败了, 调用reject(reason)
})
console.log('new Promise()之后') //这句打印主要是判断执行器中的任务是同步还是异步
p.then( // 异步执行回调任务
value => {
// 接收得到成功的value数据 onResolved
console.log('成功的回调', value)
},
reason => {
// 接收得到失败的reason数据 onRejected
console.log('失败的回调', reason)
}
2.回调地狱
/*
1. 指定回调函数的方式更加灵活:
旧的: 必须在启动异步任务前指定
promise: 启动异步任务 => 返回promie对象 => 给promise对象绑定回调函数(甚至可以在异步任务结束后指定)
2. 支持链式调用, 可以解决回调地狱问题
什么是回调地狱? 回调函数嵌套调用, 外部回调函数异步执行的结果是嵌套的回调函数执行的条件
回调地狱的缺点? 不便于阅读 / 不便于异常处理
解决方案? promise链式调用
终极解决方案? async/await
*/
//--------------------------示意----------------------------------------
//2.1. 回调地狱
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('Got the final result: ' + finalResult)
}, failureCallback)
}, failureCallback)
}, failureCallback)
//2.2. 使用promise的链式调用解决回调地狱
doSomething()
.then(function(result) {
return doSomethingElse(result)
})
.then(function(newResult) {
return doThirdThing(newResult)
})
.then(function(finalResult) {
console.log('Got the final result: ' + finalResult)
})
.catch(failureCallback)
//2.3. async/await: 回调地狱的终极解决方案
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)
}
}
3.关键问题
问题一:
/*
1. 如何改变promise的状态?
(1)resolve(value): 如果当前是pendding就会变为resolved
(2)reject(reason): 如果当前是pendding就会变为rejected
(3)抛出异常: 如果当前是pendding就会变为rejected
2. 一个promise指定多个成功/失败回调函数, 都会调用吗?
当promise改变为对应状态时都会调用
*/
const p = new Promise((resolve, reject) => {
// resolve(1) // promise变为resolved成功状态 若是resolve()虽成功,但值为undifined
// reject(2) // promise变为rejected失败状态
// throw new Error('出错了') // 抛出异常, promse变为rejected失败状态, reason为 抛出的error
throw 3 // 抛出异常, promse变为rejected失败状态, reason为 抛出的3
})
p.then(
value => {
},
reason => {
console.log('reason', reason)}
)
p.then(
value => {
},
reason => {
console.log('reason2', reason)}
)
问题二:
/*
3.改变promise状态和指定回调函数谁先谁后?
(1)都有可能, 正常情况下是先指定回调再改变状态, 但也可以先改状态再指定回调
(2)如何先改状态再指定回调?
①在执行器中直接调用resolve()/reject()
②延迟更长时间才调用then()
(3)什么时候才能得到数据?
①如果先指定的回调, 那当状态发生改变时, 回调函数就会调用, 得到数据
②如果先改变的状态, 那当指定回调时, 回调函数就会调用, 得到数据
*/
// 常规: 先指定回调函数, 后改变的状态
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1) // 后改变的状态(同时指定数据), 异步执行回调函数
}, 1000);
}).then(// 先指定回调函数, 保存当前指定的回调函数
value => {
},
reason => {
console.log('reason', reason)}
)
// 如何先改状态, 后指定回调函数
new Promise((resolve, reject) => {
resolve(1) // 先改变的状态(同时指定数据)
}).then(// 后指定回调函数, 异步执行回调函数
value => {
console.log('value2', value)},
reason => {
console.log('reason2', reason)}
)
console.log('-------')
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1) // 后改变的状态(同时指定数据), 异步执行回调函数
}, 1000);
})
setTimeout(() => {
p.then(
value => {
console.log('value3', value)},
reason => {
console.log('reason3', reason)}
)
}, 1100);
问题三:
/*
4. promise.then()返回的新promise的结果状态由什么决定?
(1)简单表达: 由then()指定的回调函数执行的结果决定
(2)详细表达:
①如果抛出异常, 新promise变为rejected, reason为抛出的异常
②如果返回的是非promise的任意值, 新promise变为resolved, value为返回的值
③如果返回的是另一个新promise, 此promise的结果就会成为新promise的结果
*/
new Promise((resolve, reject) => {
// resolve(1)
reject(1)
}).then(
value => {
console.log('onResolved1()', value)
// return 2
// return Promise.resolve(3)
// return Promise.reject(4)
throw 5
},
reason => {
console.log('onRejected1()', reason)
// return 2
// return Promise.resolve(3)
// return Promise.reject(4)
throw 5
}
).then(
value => {
console.log('onResolved2()', value)
},
reason => {
console.log('onRejected2()', reason)
}
)
问题四:
/*
5.promise如何串连多个操作任务?
(1)promise的then()返回一个新的promise, 可以开成then()的链式调用
(2)通过then的链式调用串连多个同步/异步任务
*/
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) => {
// 启动任务3(异步)
setTimeout(() => {
console.log('执行任务3(异步))')
resolve(3)
}, 1000);
})
}
).then(
value => {
console.log('任务3的结果: ', value)
}
)
问题五:
/*
6.promise异常传/穿透?
(1)当使用promise的then链式调用时, 可以在最后指定失败的回调,
(2)前面任何操作出了异常, 都会传到最后失败的回调中处理
7.中断promise链?
(1)当使用promise的then链式调用时, 在中间中断, 不再调用后面的回调函数
(2)办法: 在回调函数中返回一个pendding状态的promise对象
*/
new Promise((resolve, reject) => {
// resolve(1)
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 => Promise.reject(reason)
).catch(reason => {
console.log('onReejected1()', reason)
// throw reason
// return Promise.reject(reason)
return new Promise(() => {
}) // 返回一个pending的promise 中断promise链
}).then(
value => {
console.log('onResolved3()', value)
},
reason => {
console.log('onReejected2()', reason)
}
)
4.async与await
/*
1. async 函数
函数的返回值为promise对象
promise对象的结果由async函数执行的返回值决定
2. await 表达式
await右侧的表达式一般为promise对象, 但也可以是其它的值
如果表达式是promise对象, await返回的是promise成功的值
如果表达式是其它值, 直接将此值作为await的返回值
3. 注意:
await必须写在async函数中, 但async函数中可以没有await
如果await的promise失败了, 就会抛出异常, 需要通过try...catch来捕获处理
*/
// async函数的返回值是一个promise对象
// async函数返回的promise的结果由函数执行的结果决定
async function fn1() {
return 1
// throw 2
// return Promise.reject(3)
// return Promise.resolve(3)
/* return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(4)
}, 1000);
}) */
}
const result = fn1()
// console.log(result)
result.then(
value => {
console.log('onResolved()', value)
},
reason => {
console.log('onRejected()', reason)
}
)
function fn2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// resolve(5)
reject(6)
}, 1000);
})
}
function fn4() {
return 6
}
async function fn3() {
try {
// const value = await fn2() // await右侧表达为promise, 得到的结果就是promise成功的value
const value = await fn1()
console.log('value', value)
} catch (error) {
console.log('得到失败的结果', error)
}
// const value = await fn4() // await右侧表达不是promise, 得到的结果就是它本身
// console.log('value', value)
}
fn3()
异步队列
JS 中用来存储待执行回调函数的队列包含2 个不同特定的列队
JS为单线程引擎,任务的执行顺序:同步任务-》队列中的异步任务(微队列-》宏队列)
PS:
①每个宏队列任务执行前,都要将当前微队列中所有微任务取出先执行。
②定时器达到指定的延迟时间后,才将包含的回调任务放入宏队列。
示例
题一:
/*
宏: []->[]->[5] ->[5] ->[5] -> [5]
微: []->[]->[1] ->[1,2]->[1,2] -> []
3->3,7->3,7-> 3,7 ->3,7,4 -> 3,7,4,1,2 -> 3 7 4 1 2 5
*/
const first = () => (new Promise((resolve, reject) => {
console.log(3)
let p = new Promise((resolve, reject) => {
console.log(7)
setTimeout(() => {
console.log(5)
resolve(6) //后面没有onResolved/onRejected回调,没能打印
}, 0) //延迟为0,故立即将包含的回调放入宏队列
resolve(1)
})
resolve(2)
p.then((arg) => {
//p状态成功后,该回调放入微队列
console.log(arg)
})
}))
first().then((arg) => {
console.log(arg)
})
console.log(4)
题二:
/*
1,7,2,3,8,4,6,5,0
宏:[0] ->[0] ->
微:[2,8] ->[8,4] ->[4,6] ->[6,5]
1,7 ->1,7,2,3 ->1,7,2,3,8 ->1,7,2,3,8,4
*/
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") //在取出“2”异步任务,“3”被同步打印,可获取串连.then中的各回调函数,只不过加入微队列的前提是前一个已完成返回promise对象,否则只是先缓存
})
}).then(()=>{
console.log("6")
})
new Promise((resolve,reject)=>{
console.log("7")
resolve()
}).then(()=>{
console.log("8")
})