promise特点:1异步2状态只能改变一次3.穿透问题,对比async...await的执行顺序

真题1:

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

运行结果:

1

考点点拨:Promise 值穿透问题

then 方法的入参只能是函数。万一你想塞给它一些乱七八糟的东西,它就会“翻脸不认人”。

具体到我们这个题里,第一个 then 方法中传入的是一个 Promise 对象,then 说:”我不认识“;第二个 then 中传入的是一个数字, then 继续说”我不认识“;第四个干脆啥也没穿,then 说”入参undefined了,拜拜“;直到第五个入参,一个函数被传了进来,then 哭了:”终于等到一个我能处理的!“,于是只有最后一个入参生效了。

在这个过程中,我们最初 resolve 出来那个值,穿越了一个又一个无效的 then 调用,就好像是这些 then 调用都是透明的、不存在的一样,因此这种情形我们也形象地称它是 Promise 的“值穿透”。

 

真题2:

const promise = new Promise((resolve, reject) => {
  resolve('第 1 次 resolve')
  console.log('resolve后的普通逻辑')
  reject('error')
  resolve('第 2 次 resolve')
})
 
promise
.then((res) => {
  console.log('then: ', res)
})
.catch((err) => {
  console.log('catch: ', err)
})

运行结果:

resolve后的普通逻辑
then:  第 1 次 resolve

考点点拨:Promise 对象的状态只能被改变一次

 

真题3:

const promise = new Promise((resolve, reject) => {
    console.log(1);
    resolve();
    console.log(2);
});

promise.then(() => {
    console.log(3);
});

console.log(4);

运行结果:

1
2
4
3

 考点点拨:Promise 传入的excutor函数本身是同步,只有then里面是异步,而且只有执行了resolve方法,才会进入then。async。。。。await                中await +后边函数,就类似于new Promise(),而await+函数,后边的语句就类似于then函数

真题4:

async function async1() {
  console.log("AAAA");
  await async2();  //  await new Promise(function(resolve) { resulve(undefined) })
  console.log("BBBB");
}
async function async2() {
  console.log("CCCC");
}


console.log("DDDD");
async1();
console.log('EEEE')
VM418:11 DDDD
VM418:2 AAAA
VM418:7 CCCC
VM418:13 EEEE
VM418:4 BBBB

真题5:

async function async1() {
  console.log("AAAA");
  await async2();  //  await new Promise(function(resolve) { resulve(undefined) })
  console.log("BBBB");
}
async function async2() {
setTimeout(function(){console.log('CCCC')},0)

}
console.log("DDDD");
async1();
console.log('EEEE')

VM594:12 DDDD
VM594:2 AAAA
VM594:14 EEEE
VM594:4 BBBB
VM594:7 CCCC

 

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值