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

การสร้าง Promise ที่ resolve/reject ตามเงื่อนไข - JavaScript

ฟังก์ชันนี้จำลอง 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));

การทำงาน

  1. สร้าง Promise ใหม่
  2. ใช้ setTimeout จำลอง async operation (3 วินาที)
  3. ตรวจสอบเงื่อนไข resolve/reject
  4. ใช้ .then()/.catch() จัดการผลลัพธ์

ผลลัพธ์

success
failure

ประยุกต์ใช้: การจัดการ asynchronous operations API calls การ validate ข้อมูลแบบ async