Promise的记录和理解

179 阅读1分钟

promise 介绍执行过程

 new Promise((reslove,reject)=>{
  reslove();
  Promise.resolve().then(()=>{
    console.log(1);
  })
  console.log(0);
}).then(()=>{
  console.log(2);
})

结果为0,1,2

理由:

Promise的参数 回调函数 是同步的 还有then这个方法也是同步的

Promise中的 回调函数 Promise.resolve().then()会压入微任务队列。然后打印console.log(0),这个时候整个Promise执行完毕。在把自身的then中的回调函数压入队列 开始执行: 首先把队列中 1 打印出来 最后是 2

Promise的2种使用方式

Promise.resolve(Promise.resolve(4)).then((res)=>{
  console.log(res);
})

Promise.resolve参数可以接收一个Promise 并且 返回就是参数中的Promise打印4

new Promise((resolve,reject)=>{
  resolve();
  Promise.resolve({
    then:function(reslove,reject){
      console.log(1);
      reslove()
    }
  }).then(()=>{
    console.log(3);
  })
  console.log(0);
}).then(()=>{
  console.log(2);
})

结果为0,1,2,3

理由:同样的先会把Promise 回调函数 执行 Promise.resolve().then()会压入微任务队列。然后执行console.log(0)整个Promise执行完毕。在把自身的then中的回调函数压入队列 开始执行:首先把1打印出来 发现 又是个Promise 这个Promise执行完毕 把自身then中的回调函数压入队列 然后打印2 最后就是把这个3 打印出来


总结:

Promise 中的 回调函数是同步 并且 then这个方法不是异步的 then的参数 回调函数是异步的。