1. 程式人生 > 實用技巧 >setTimeout、Promise、Async/Await 的區別

setTimeout、Promise、Async/Await 的區別

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