1、JS是单线程语言,包括同步任务、异步任务,异步任务又包括宏观任务和微观任务
2、执行顺序:同步任务——>微观任务——>宏观任务
3、宏观任务的方法有:script(整体代码)、setTimeout、setInterval、I/O、UI交互事件、postMessage、MessageChannel、setImmediate(Node.js 环境)
4、微观任务的方法有:Promise.then、MutaionObserver、process.nextTick(Node.js 环境),async/await实际上是promise+generator的语法糖,也就是promise,也就是微观任务
1. setTimeout
console.log('script start') //1. 打印 script start setTimeout(function(){ console.log('settimeout') // 4. 打印 settimeout }) // 2. 调用 setTimeout 函数,并定义其完成后执行的回调函数 console.log('script end') //3. 打印 script start // 输出顺序:script start->script end->settimeout
2. Promise
console.log('script start') let promise1 = new Promise(function (resolve) { console.log('promise1') resolve() console.log('promise1 end') }).then(function () { console.log('promise2') }) setTimeout(function(){ console.log('settimeout') }) console.log('script end') // 输出顺序: script start->promise1->promise1 end->script end->promise2->settimeout
3. async/await
async function async1(){ console.log('async1 start'); await async2(); console.log('async1 end') } async function async2(){ console.log('async2') } console.log('script start'); async1(); console.log('script end') // 输出顺序:script start->async1 start->async2->script end->async1 end