Node Promise
📌 1. 基本概念
Promise 是 ES6 引入的非同步編程解法,用來避免 callback hell。
一個 Promise 物件表示一個尚未完成但預期會完成的操作結果。
狀態 | 說明 |
---|---|
pending | 初始狀態,尚未結束 |
fulfilled | 操作成功完成(resolve) |
rejected | 操作失敗(reject) |
const promise = new Promise((resolve, reject) => {
if (someCondition) resolve('成功');
else reject('錯誤');
});
📌 2. Promise 執行順序與事件循環(Event Loop)
類型 | 分類 | 優先順序 |
---|---|---|
.then, .catch, .finally | Microtask | 高(在 macrotask 後立即執行) |
setTimeout, setImmediate | Macrotask | 較低 |
console.log('start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('end');
✅ 預期輸出:
start
end
promise
timeout
📌 3. async/await 是怎麼實現的?
- async 函數本質上會回傳一個 Promise。
- await 會暫停該函數執行,等待 Promise resolve,再繼續執行後續程式。
async function main() {
console.log('1');
await Promise.resolve();
console.log('2');
}
main();
console.log('3');
✅ 預期輸出:
1
3
2
❗ await 會將後續程式包進 microtask queue!