关于promise的一道面试题

Promise.resolve(1)  
.then(2)  
.then(Promise.resolve(3))  
.then(console.log)

运行结果:

   1

解释:.then 或者 .catch 的参数期望是函数,传入非函数则会发生值穿透。

Promise.resolve(1)
  .then(function(){return 2})
  .then(Promise.resolve(3))
  .then(console.log)

结果为2

Promise.resolve(1)
  .then(function(){return 2})
  .then(function(){return Promise.resolve(3)})
  .then(console.log)

结果为3

不是太明白,then里面必须通过函数来返回的一个值才能被包装为Promise吗?


慕桂英4014372
浏览 1717回答 3
3回答

慕斯卡2128210

只要.then的参数是函数,而且函数内部就返回值,那么这一个.then就会被执行,上一个.then返回什么值都不需要理会(除非此.then的参数需要上一个.then的return返回来)
打开App,查看更多内容
随时随地看视频慕课网APP