老师有几道面试的需要问一下
来源:7-4 JS 异步相关的面试题

Raymond0913
2021-11-25
1.我答案是执行.catch
为啥会执行.then
Promise.resolve()
.then(()=>{
return new Error('error!!!!')
})
.then((res)=>{
console.log('then',res) //then Error: error!!!!
})
.catch((err)=> {
console.log('catch',err)
})
2. 这里的错误提示是Chaining cycle detected for promise #<Promise>
这个错误我都没见过。我不知道为何会输出这个
const promise = Promise.resolve()
.then(()=>{
return promise
})
promise.catch(console.error)
3. 第一个我认为是throw new Error('errpr')后执行.catch
答案也正确,但下面有个变种把我搞蒙了
Promise.resolve()
.then(function success (res) {
throw new Error('error')
},function fail1 (e){
console.error('fail1',e)
})
.catch(function fail2 (e) {
console.log('fail2',e) // fail2 Error: error
})
变种
Promise.resolve()
.then(function success (res) {
throw new Error('error')
},function fail1 (e){
console.error('fail1',e)
})
.then(function success2 (res){
},function fail2(e){
console.log('fail2',e) //fail2 Error: error
})
这里为什么会执行.then
上面代码和前面一样。前面执行.catch
这里执行.then
,而且我在.then
里第一个函数success2
中加入console.log("success")
也不执行,结果与不加没有区别
4.
这里没问题
var p = new Promise((resolve, reject)=>{
reject(Error('The Fails!'))
})
p.catch(error=>console.log(error.message)) //The Fails!
p.catch(error=>console.log(error.message)) //The Fails!
这里的答案不理解,为什么后面的两个p.catch语句不执行了。
var p = new Promise((resolve, reject)=>{
return Promise.reject(Error('The Fails!')) //这里执行The Fails!
})
p.catch(error=>console.log(error.message))
p.catch(error=>console.log(error.message))
这里答案也不理解,为什么,.catch
的执行没有return
但.then
能够执行
var p = new Promise((resolve, reject)=>{
reject(Error('The Fails!'))
})
.catch(error => console.log(error)) //Error: The Fails!
.then(error => console.log(error)) //undefined
希望老师解答一下。有些题错了,敲一下,debugger一下也就知道了。但这几个没搞明白。
写回答
1回答
-
双越
2021-11-26
你先带着问题继续学习,第 8 章会详细解释 Promise 。
012021-11-26
相似问题