單執行緒的狀況下- 習慣的思維
| const userTable = { '1': { money: 10000 } } |
| |
| function withdraw (id, money) { |
| userTable[id].money -= money |
| } |
| |
| function deposit (id, money) { |
| const currentMoney = userTable[id].money |
| currentMoney += money |
| userTable[id].money = currentMoney |
| } |
多執行緒的狀況下- 沒有互斥鎖的狀況
| const money1 = userTable[id].money |
| const money2 = userTable[id].money |
| money1 -= 10000 |
| userTable[id].money = money1 |
| |
| money2 += 1000 |
| userTable[id].money = money2 |
| |
| |
Event Loop (事件循環機制)

| function bar () { console.log('baz') } |
| function foo () { bar() } |
| setTimeout(() => { console.log('setTimeout') }, 1000) |
| setInterval(() => { console.log('setInterval') }, 5000) |
| foo() |
小試身手
- Task(Macrotask): setTimeout, requestAnimation …
- Microtask: Promise.then, process.nextTick …
| setTimeout(() => { |
| console.log('setTimeout') |
| }) |
| |
| new Promise(resolve => { |
| console.log('promise executor') |
| resolve() |
| }) |
| .then(() => { |
| console.log('promise then') |
| }) |
| |
| console.log('main') |
歡迎來到真實世界
請寫出以下印出 0~9 的順序
| async function async1() { |
| new Promise(async resolve => { |
| Promise.resolve() |
| .then(() => { |
| console.log(0) |
| resolve() |
| }) |
| }) |
| .then(() => { |
| console.log(1) |
| }) |
| await async2() |
| console.log(2) |
| } |
| async function async2() { |
| async3() |
| console.log(3) |
| } |
| function async3() { |
| new Promise((resolve) => resolve()) |
| .then(() => { |
| console.log(4) |
| }) |
| Promise.resolve() |
| .then(() => { |
| console.log(5) |
| }) |
| } |
| |
| async1() |
| |
| setTimeout(function() { |
| console.log(6) |
| }, 0) |
| |
| new Promise(resolve => { |
| console.log(7) |
| resolve() |
| }) |
| .then(function() { |
| console.log(8) |
| }) |
| .then(function() { |
| console.log(9) |
| }) |
其他挑戰
非同步機制
{"metaMigratedAt":"2023-06-15T05:41:04.538Z","metaMigratedFrom":"Content","title":"非同步機制","breaks":true,"contributors":"[{\"id\":\"e77f9ae0-feb2-4c38-9ae8-f06f8655e3a4\",\"add\":14138,\"del\":10631}]"}