主任务>微任务>宏任务。执行完所有主任务才会执行微任务,微任务顺序执行。 promise(主任务)!!!!和Promise外主任务同等优先级。then会加入临时微任务队尾,遇到一个加一个,并不会将某一个promise后所有then一次性加入微任务队列,优先级还是大于宏任务。 resolve,reject把任务放进微任务队列中, new promise(主任务).then(result,err).then(result,err).then(…) //每一个Promise.then也是一个Promise…,then顺利执行完成后对应resolve状态,下一个then中执行resolve对应内容 (1)当前一个then中的代码都是同步执行的,执行结束后第二个then即可注册进入微任务队列。 (2) 当前一个then中有return 关键字,需要return的内容完全执行结束 (若是个promise,也要执行完成),第二个then才会注册进入微任务队列。 第一个then的回调监听最新Promise对象的resolve执行后才注册进微任务队列,之后的then回调都依赖于前一个then中的代码执行结束。 说明(:数字:)为执行顺序,(:字母:)为输出顺序
console.log('*********************************************************')
setTimeout(() => { //宏任务1
console.log("主要是看宏任务什么时候执行") //(:16:) (:g:)
}, 0);
debugger
var p1 = new Promise((res, rej) => { //主任务1 (:1:)
res('promise 1 的 then1')
}).then(res => { //(:2:)第1个加入微任务队列;(:5:)执行微任务
console.log(res) //(:a:) 输出'promise 1 的 then1'
new Promise((res, rej) => { //(:6:)执行微任务中的主任务
res('promise 1 的子promise1-2 的 then1')
}).then(v => { //(:7:)第3个加入微任务队列 (:12:)执行微任务
console.log(v) //(c:) 输出'promise 1 的子promise1-2 的 then1'
return 'promise1-2 的 then2 '
}).then(v => { //(:13:)第6个加入微任务队列 (:16:)执行微任务
console.log(v) //(:f:) 输出'promise1-2 的 then2' ===>结束
})
return 'prmise 1 的 then2' //(:8:)
}).then(v => { // (:9:)第4个加入微任务队列 (:14:)执行微任务
console.log(v) //(:d:) 输出'prmise 1 的 then2'
})
var p2 = new Promise((res, rej) => {
res('promise 2 的 then 1') //主任务2 (:3:)
}).then(res => { //(:4:)第2个加入微任务队列 (:10:)执行微任务
console.log(res) //(:b:) 输出'promise 2 的 then1'
return 'promise 2 的 then 2'
}).then(v => { //(:11:)第5个加入微任务队列 (:15:)执行微任务
console.log(v) //(:e:) 输出'promise 2 的 then 2'
})
setTimeout(()=>console.log('a'))
Promise.resolve().then(
()=>console.log('b')
).then( //下一个then依赖该then返回的结果,return后才执行下一个then
()=>Promise.resolve('c').then(
(data)=>{
setTimeout(()=>console.log('d'));
console.log('f')
return data
}
)
).then(data=>console.log(data))