LLwanran / front_end_studying

前端知识要点
https://llwanran.github.io/front_end_studying/
2 stars 1 forks source link

Promise 构造函数是同步执行还是异步执行,那么 then 方法呢? #50

Open LLwanran opened 5 years ago

LLwanran commented 5 years ago
const promise = new Promise((resolve, reject) => {
  console.log(1)
  resolve()
  console.log(2)
})

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

console.log(4)

执行结果是:1243 promise构造函数是同步执行的,then方法是异步执行的

LLwanran commented 5 years ago

这里对上面的例子做一个扩展

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

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

console.log(4);

setTimeout(function() {
  console.log(6);
});

执行结果: 124536