老师有几道面试的需要问一下

来源: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 。

0
1
Raymond0913
老师,第一题,我知道了是return new Error('error!!!!') 这里返回了fulfilled。是因Error对象本身不是错误?所以返回reject throw new Error('error') 抛出错误返回rejected,还有我在您的代码和例题中没有看到promise使用了return 且我看网上一个帖子说"无需在 new Promise() 中使用 return 语句" 所以这种语法有问题吗? 第二题,我已经知道了不能这么使用。所以会报错。 第三题:promise的status 会变成fulfilled,throw new Error('error') 我理解中应该会把status变成rejected。为什么变成了fulfilled,以及为什么在上面代码不变的情况下他既可以执行.then 下面代码又会执行.catch 第四题: 第二个代码,我打印p后发现promise一直停留在pending 状态。所以下面的.catch不执行。但为什么会一直停留在pending状态呢?是因为错误中断了执行吗?和第一题一样,我有些搞不懂return后到底会返回什么了。 第三个代码我理解了为什么会去执行.then 因为.catch执行返回fulfilled 但为什么.then中会打印undefined即error的值为undefined? 希望老师答疑解惑
2021-11-26
共1条回复

一天时间高效准备前端技术一面 匹配大厂面试要求

针对时下面试高频考点,帮助新人js面试快速通关

4694 学习 · 1681 问题

查看课程