Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การใช้ finally บน Promise กับ then และ catch ใน JavaScript

เมื่อ promise settled (fulfilled หรือ rejected) callback ใน finally จะถูกเรียก finally() ก็คืน Promise ด้วย

ให้โค้ดรันได้ทั้งสำเร็จและล้มเหลวเมื่อ Promise จัดการเสร็จแล้ว

ตัวอย่าง

new Promise(    (resolve) => setTimeout(resolve("success"), 1000) ).then(val => console.log(val)).finally(() => console.log("Promise complete!"))

ผลลัพธ์

success Promise complete!

ดูกรณี promise ล้มเหลว

ตัวอย่าง

// No method get on undefined. This will throw an error new Promise(() => undefined.get())    .then(val => console.log(val))    .catch(err => console.log("Failed!"))    .finally(() => console.log("Promise complete!"))

ผลลัพธ์

Failed! Promise complete!

สังเกตว่าทั้งสำเร็จและล้มเหลว finally ก็ทำงาน