首先对于为啥有promise,为啥要用就不说了
首先 setTimeout 和 Promise 并不在一个异步队列中,前者属于宏任务(MacroTask),而后者属于微任务(MicroTask)。
(1) 先聊聊promise的then()是啥,其实他也是一个promise
<script>
let p1 = new Promise((resolve,reject)=>{
resolve("fulfilled");
});
let p2 = p1.then(
value => console.log(value);
reason => console.log(reason);
)
console.log(p1);
console.log(p2);//输出是新创建的promise对象
setTimeout(() => {
console.log(p1);
console.log(p2);//输出的是已解决状态的promise
);
</script>
此时timeout函数是宏任务,timeout微任务早于宏任务,所以输出已解决的promise
(2) then的链式操作,then是promise所以then后面可以再打点调用then(),后面的then就是上面then这个(promise)的then[then之所以用.调用就是因为他是对象]
then后面的then就是只要前面的then的状态的处理,所以后面就会返回成功