สัญญาจาวาสคริปต์


สารบัญ

    แสดงสารบัญ

"ฉันสัญญาว่าจะได้ผล!"

"การสร้างโค้ด" คือโค้ดที่อาจใช้เวลาพอสมควร

“รหัสการบริโภค” คือรหัสที่ต้องรอผล

A Promise คืออ็อบเจ็กต์ JavaScript ที่เชื่อมโยงการสร้างโค้ดและการใช้โค้ด

วัตถุสัญญา JavaScript

วัตถุ JavaScript Promise มีทั้งรหัสการผลิตและการเรียกรหัสที่ใช้งาน:

ไวยากรณ์สัญญา

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

  myResolve(); // when successful
  myReject();  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

เมื่อโค้ดการผลิตได้รับผลลัพธ์ ควรเรียกหนึ่งในสองคอลแบ็ก:

Success

myResolve (มูลค่าผลลัพธ์)

Error

myReject (วัตถุผิดพลาด)


คุณสมบัติของวัตถุสัญญา

อ็อบเจ็กต์ JavaScript Promise สามารถเป็น:

  • รอดำเนินการ

  • สำเร็จ

  • ถูกปฏิเสธ

ออบเจ็กต์ Promise รองรับสองคุณสมบัติ: สถานะ และ ผลลัพธ์

ในขณะที่ออบเจ็กต์ Promise อยู่ในสถานะ "รอดำเนินการ" (ทำงาน) แต่ผลลัพธ์ไม่ได้ถูกกำหนดไว้

เมื่อออบเจ็กต์ Promise "บรรลุผล" ผลลัพธ์จะเป็นค่า

เมื่อวัตถุ Promise ถูก "ปฏิเสธ" ผลลัพธ์จะเป็นวัตถุที่มีข้อผิดพลาด

"pending"

ไม่ได้กำหนด

"fulfilled"

ค่าผลลัพธ์

"rejected"

วัตถุที่มีข้อผิดพลาด

คุณไม่สามารถเข้าถึงคุณสมบัติของสัญญา สถานะ และ ผลลัพธ์

คุณต้องใช้วิธี Promise เพื่อจัดการกับคำสัญญา


สัญญาว่าจะทำอย่างไร

นี่คือวิธีการใช้สัญญา:

myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

Promise.then() รับสองอาร์กิวเมนต์ การโทรกลับเพื่อความสำเร็จและอีกข้อหนึ่งสำหรับความล้มเหลว

ทั้งสองเป็นทางเลือก ดังนั้นคุณจึงสามารถเพิ่มการโทรกลับเมื่อสำเร็จหรือล้มเหลวเท่านั้น

ตัวอย่าง

function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

let myPromise = new Promise(function(myResolve, myReject) {
  let x = 0;

// The producing code (this may take some time)

  if (x == 0) {
    myResolve("OK");
  } else {
    myReject("Error");
  }
});

myPromise.then(
  function(value) {myDisplayer(value);},
  function(error) {myDisplayer(error);}
);

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Promise</h2>

<p id="demo"></p>

<script>
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

let myPromise = new Promise(function(myResolve, myReject) {
  let x = 0;

// some code (try to change x to 5)

  if (x == 0) {
    myResolve("OK");
  } else {
    myReject("Error");
  }
});

myPromise.then(
  function(value) {myDisplayer(value);},
  function(error) {myDisplayer(error);}
);
</script>

</body>
</html>


ตัวอย่างสัญญา JavaScript

เพื่อสาธิตการใช้คำสัญญา เราจะใช้ตัวอย่างการติดต่อกลับจากบทที่แล้ว:

  • กำลังรอการหมดเวลา

  • กำลังรอไฟล์


กำลังรอการหมดเวลา

ตัวอย่างการใช้การโทรกลับ

setTimeout(function() { myFunction("I love You !!!"); }, 3000);

function myFunction(value) {
  document.getElementById("demo").innerHTML = value;
}

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>
<h2>setInterval() with a Callback</h2>

<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>

<h1 id="demo"></h1>

<script>
setTimeout(function() { myFunction("I love You !!!"); }, 3000);

function myFunction(value) {
  document.getElementById("demo").innerHTML = value;
}
</script>

</body>
</html>

ตัวอย่างการใช้คำสัญญา

let myPromise = new Promise(function(myResolve, myReject) {
  setTimeout(function() { myResolve("I love You !!"); }, 3000);
});

myPromise.then(function(value) {
  document.getElementById("demo").innerHTML = value;
});

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Promise</h2>

<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>

<h1 id="demo"></h1>

<script>
const myPromise = new Promise(function(myResolve, myReject) {
  setTimeout(function(){ myResolve("I love You !!"); }, 3000);
});

myPromise.then(function(value) {
  document.getElementById("demo").innerHTML = value;
});
</script>

</body>
</html>

กำลังรอไฟล์

ตัวอย่างการใช้ Callback

function getFile(myCallback) {
  let req = new XMLHttpRequest();
  req.open('GET', "mycar.html");
  req.onload = function() {
    if (req.status == 200) {
      myCallback(req.responseText);
    } else {
      myCallback("Error: " + req.status);
    }
  }
  req.send();
}

getFile(myDisplayer);

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Callbacks</h2>

<p id="demo"></p>

<script>
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

function getFile(myCallback) {
  let req = new XMLHttpRequest();
  req.onload = function() {
    if (req.status == 200) {
      myCallback(this.responseText);
    } else {
      myCallback("Error: " + req.status);
    }
  }
  req.open('GET', "mycar.html");
  req.send();
}

getFile(myDisplayer); 
</script>

</body>
</html>

ตัวอย่างการใช้ Promise

let myPromise = new Promise(function(myResolve, myReject) {
   
  let req = new XMLHttpRequest();
   
  req.open('GET', "mycar.htm");
   
  req.onload = function() {
       
    if (req.status == 200) {
           
      myResolve(req.response);
       
    } else {
           
      myReject("File not Found");
       
    }
  };
  req.send();
});

myPromise.then(
   
  function(value) {myDisplayer(value);},
   
  function(error) {myDisplayer(error);}
);

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Promise</h2>

<p id="demo"></p>

<script>
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

let myPromise = new Promise(function(myResolve, myReject) {
  let req = new XMLHttpRequest();
  req.open('GET', "mycar.html");
  req.onload = function() {
    if (req.status == 200) {
      myResolve(req.response);
    } else {
      myReject("File not Found");
    }
  };
  req.send();
});

myPromise.then(
  function(value) {myDisplayer(value);},
  function(error) {myDisplayer(error);}
);
</script>

</body>
</html>

รองรับเบราว์เซอร์

ECMAScript 2015 หรือที่รู้จักในชื่อ ES6 ได้เปิดตัวออบเจ็กต์ JavaScript Promise

ตารางต่อไปนี้กำหนดเบราว์เซอร์เวอร์ชันแรกที่รองรับออบเจ็กต์ Promise อย่างเต็มรูปแบบ:

Chrome 33 Edge 12 Firefox 29 Safari 7.1 Opera 20
Feb, 2014 Jul, 2015 Apr, 2014 Sep, 2014 Mar, 2014