我的promise理解

213 阅读1分钟

直接promise时

setTimeout(() => {
  console.log(1);
}, 0);
new Promise(() => {
  console.log(2);
}).then(() => {
  console.log(3);
});
console.log(4);    //. 2->4->1

Promise 在创建的时候就立即执行了,所以第一个输出2,由于传入的函数中没有reslove和reject参数,所以.then中的回调函数并没有执行,所以3没有打印。

setTimeout将回调函数推入执行栈的最后,所以最后打印1

有reslove调用时

setTimeout(() => {
  console.log(1);
}, 0);
new Promise((resl, rej) => {
  console.log(2);
  resl();
}).then(() => {
  console.log(3);
});
console.log(4);//2->3->4->1

promise的参数中加入了reslove参数,所以then的回调能被执行。

在promise中加入setTimeOut

setTimeout(() => {
  console.log(1);
}, 0);
new Promise((resl, rej) => {
  console.log(2);
  setTimeout(() => {
    console.log(5);
  }, 0);
  resl();
}).then(() => {
  console.log(3);
});
console.log(4);//2->4->3->1->5