从MDN的文档或者是其他的Web教学的网站看到的教学,Promise对象往往和“异步”挂钩。但是Promise对象本体内的代码其实是同步执行的,只有then方法或者catch方法才是异步执行,下面通过一个简单的例子来了解。
请说出下面这段代码的执行结果:
new Promise(function(resolve){ console.log(1); resolve(); }).then(function(){ console.log(2); }).then(function(){ console.log(3); }) console.log(4);
正确答案如下:
1 4 2 3
由上面例子可得出结论,Promise对象内部的代码是同步执行的,但是Promise对象的then以及catch方法是异步执行的。then以及catch的执行是固定被放到异步任务队列中的。