Promises
Promise คืออะไร?
หัวข้อที่มีชื่อว่า “Promise คืออะไร?”Promise คือออบเจ็กต์ที่แทนค่าที่จะพร้อมใช้งานในอนาคต มีสามสถานะ:
- Pending — งานยังดำเนินอยู่
- Fulfilled — งานสำเร็จ Promise ถือค่าผลลัพธ์ไว้
- Rejected — งานล้มเหลว Promise ถือ error ไว้
Promise เปลี่ยนจาก pending ไปเป็น fulfilled หรือ rejected — แล้วไม่ย้อนกลับ เมื่อ settle แล้วจะคงอยู่อย่างนั้น
var p = new Promise(function(resolve, reject) { // เรียก resolve(value) เพื่อ fulfill หรือ reject(error) เพื่อ reject resolve('hello');});การ chain ด้วย .then / .catch / .finally
หัวข้อที่มีชื่อว่า “การ chain ด้วย .then / .catch / .finally”.then(onFulfilled) คืน Promise ใหม่ ทำให้ chain ขั้นตอนต่อกันได้ .catch(onRejected) จัดการการ reject .finally(fn) ทำงานไม่ว่าผลจะเป็นอย่างไร — มีประโยชน์สำหรับการ cleanup
fetchData() .then(function(data) { return process(data); }) .then(function(result) { console.log('Done:', result); }) .catch(function(err) { console.error('Failed:', err.message); }) .finally(function() { console.log('Cleanup'); });Promise combinator
หัวข้อที่มีชื่อว่า “Promise combinator”| Combinator | พฤติกรรม |
|---|---|
Promise.all(arr) | resolve เมื่อทุกตัว resolve; reject ทันทีที่มีตัวแรก reject |
Promise.race(arr) | settle ด้วย Promise ตัวแรกที่ settle (ไม่ว่า fulfilled หรือ rejected) |
Promise.allSettled(arr) | resolve เมื่อทุกตัว settle; ให้ผลของแต่ละตัว (ไม่เคย reject) |
Promise.any(arr) | resolve ด้วยตัวแรกที่ fulfilled; reject เฉพาะเมื่อทุกตัว reject |
เดโมที่รันได้
หัวข้อที่มีชื่อว่า “เดโมที่รันได้”สนิปเป็ตสร้าง Promise สองตัวที่ resolve ทันทีด้วยค่าคงที่ chain ด้วย .then ใช้ Promise.all และเพิ่ม .finally สำหรับ cleanup
ผลลัพธ์จะเป็นเสมอ: Fetched: data-A, แล้ว All done: data-A and data-B, แล้ว Finally: cleanup