JS:异步和事件循环练习题2(*****五颗星)
1.第1题:
<script>
Promise.reject('err!!!')
.then((res) => {
console.log('success', res)
}, (err) => {
console.log('error', err)
}).catch(err => {
console.log('catch', err)
})
// 结果:error err!!!
</script>
.then函数中的两个参数:
- 第一个参数是用来处理Promise成功的函数
- 第二个则是处理失败的函数
也就是说Promise.resolve('1')的值会进入成功的函数,Promise.reject('2')的值会进入失败的函数。
在这道题中,错误直接被then的第二个参数捕获了,所以就不会被catch捕获了,输出结果为:error err!!!'
<script>
Promise.resolve()
.then(function success(res) {
throw new Error('error!!!')
}, function fail1(err) {
console.log('fail1', err)
}).catch(function fail2(err) {
console.log('fail2', err)
})
// 结果:fail2 Error: error!!!
</script>
在then的第一参数中抛出了错误,那么他就不会被第二个参数捕获,而是被后面的catch捕获到。
2.第2题:
<script>
Promise.resolve('1')
.then(res => {
console.log(res)
})
.finally(() => {
console.log('finally')
})
Promise.resolve('2')
.finally(() => {
console.log('finally2')
return '我是finally2返回的值'
})
.then(res => {
console.log('finally2后面的then函数', res)
})
// 结果: 1 finally2 finally finally2后面的then函数 2
</script>
.then()和.finally()这两个谁在前,就先执行谁。
finally()一般用的很少,只要记住以下几点就可以了:
- .finally()方法不管Promise对象最后的状态如何都会执行
- .finally()方法的回调函数不接受任何的参数,也就是说你在.finally()函数中是无法知道Promise最终的状态是resolved还是rejected的
- 它最终返回的默认会是一个上一次的Promise对象值,不过如果抛出的是一个异常则返回异常的Promise对象。
- finally本质上是then方法的特例
<script>
Promise.resolve('1')
.finally(() => {
console.log('finally1')
throw new Error('我是finally中抛出的异常')
})
.then(res => {
console.log('finally后面的then函数', res)
})
.catch(err => {
console.log('捕获错误', err)
})
//结果: finally1 捕获错误 Error: 我是finally中抛出的异常
</script>
3.第3题:
<script>
function runAsync(x) {
return new Promise(
r => setTimeout(() => r(x, console.log(x)), 1000)
)
}
Promise.all([runAsync(1), runAsync(2), runAsync(3)])
.then(res => console.log(res))
//结果: 1 2 3 [1,2,3]
</script>
首先,定义了一个Promise,来异步执行函数runAsync,该函数传入一个值x,然后间隔一秒后打印出这个x。
之后再使用Promise.all来执行这个函数,执行的时候,看到一秒之后输出了1,2,3,同时输出了数组[1, 2, 3],三个函数是同步执行的,并且在一个回调函数中返回了所有的结果。并且结果和函数的执行顺序是一致的。
4.第4题:
<script>
function runAsync(x) {
const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
return p
}
function runReject(x) {
const p = new Promise((res, rej) => setTimeout(() => rej(`Error: ${x}`, console.log(x)), 1000 * x))
return p
}
Promise.all([runAsync(1), runReject(4), runAsync(3), runReject(2)])
.then(res => console.log(res))
.catch(err => console.lo
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
前端面试题 文章被收录于专栏
前端面试的一些常问问题、问题的具体实现(可直接运行)以及底层原理
