ฟังก์ชันนี้จำลอง network request ด้วย setTimeout และคืน Promise ที่ resolve เมื่อคำนวณถูกต้อง reject เมื่อผิด
ตัวอย่างโค้ด
const num1 = 45, num2 = 48;
const res = 93;
const expectedSumToBe = (num1, num2, res) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (num1 + num2 === res) {
resolve('success');
} else {
reject('failure');
}
}, 3000);
});
};
// การใช้งาน
expectedSumToBe(num1, num2, res)
.then(data => console.log(data))
.catch(err => console.log(err));
expectedSumToBe(23, 56, 76)
.then(data => console.log(data))
.catch(err => console.log(err));
การทำงาน
- สร้าง Promise ใหม่
- ใช้
setTimeoutจำลอง async operation (3 วินาที) - ตรวจสอบเงื่อนไข resolve/reject
- ใช้
.then()/.catch()จัดการผลลัพธ์
ผลลัพธ์
success failure
ประยุกต์ใช้: การจัดการ asynchronous operations API calls การ validate ข้อมูลแบบ async