JavaScript是一門單執行緒執行的編程語言,也就是說,同一時間只能做一件事,
1.同步任務和異步任務
1.同步任務(synchronous)
2.異步任務(asynchronous)
2. 同步任務和異步任務的執行程序

JavaScript 主執行緒從“任務佇列”中讀取異步 任務的回呼函式,放到執行堆疊中依次執行 ,這個程序是回圈不斷的,所以整個的這種運行機 制又稱為 EventLoop (事件回圈)
案例:判斷輸出順序
import thenFs from 'then-fs'
console.log('a');
thenFs.readFile('1.txt', 'utf-8').then(dataStr => {
console.log('b');
})
setTimeout(() => {
console.log('c');
}, 0)
console.log('d');
3.1宏任務和微任務

3.2宏任務和微任務的執行順序

setTimeout(() => {
console.log('1');
})
new Promise(res => {
console.log('2');
res()
}).then(() => {
console.log('3');
})
console.log('4');
console.log('1');//
setTimeout(() => {
console.log('2');//
new Promise(resolve => {
console.log('3');//
resolve()
}).then(() => {
console.log('4');//
})
})
new Promise(resolve => {
console.log('5');//
resolve()
}).then(() => {
console.log('6');//
})
setTimeout(() => {
console.log('7');//
new Promise(resolve => {
console.log('8');//
resolve()
}).then(() => {
console.log('9');//
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/330346.html
標籤:其他
