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

JavaScript ไม่มี sleep(): ใช้ Promise และ async/await แทน

หากมาจากภาษาอื่นที่มี sleep() native method สำหรับ pause execution JavaScript ไม่มี method นี้ แต่สามารถจำลองได้ 2 วิธี: Promises และ async/await

Asynchronous Functions และ setTimeout()

JavaScript เป็น single-threaded: มี call stack และ memory heap เพียงอันเดียว อ่านโค้ดบรรทัดต่อบรรทัด ต้อง execute เสร็จก่อนจึงไปบรรทัดถัดไป = synchronous by nature

Synchronous vs Asynchronous

// synchronous
console.log("First");
console.log("Second");
console.log("Third");

พิมพ์ตามลำดับ เพราะ JS execute ตามลำดับ

อยากให้บรรทัดที่ 2 พิมพ์ก่อนบรรทัดที่ 3? ใช้ setTimeout():

console.log("First");
setTimeout(() => {
  console.log("Third");
}, 1000);
console.log("Second");

setTimeout() execute callback หลังเวลาที่กำหนด (ms) โดยไม่ block thread โค้ดอื่นทำงานต่อได้

setTimeout ทำงาน 3 ขั้นตอน: 1) ตั้ง timer background 2) รันโค้ดอื่นต่อ 3) execute callback เมื่อ timer หมด

Promises

Promises ทำ asynchronous logic Promise constructor รับ callback function ที่มี 2 parameters: resolve และ reject

สร้าง Promise

console.log("before promise");
let promise = new Promise((resolve, reject) => {
  let resolvedFlag = false; // flag สำหรับทดสอบ
  console.log("first");
  console.log("second");
  console.log("third");
  console.log("fourth");
  resolvedFlag = true;
  
  if (resolvedFlag) {
    resolve("Promise resolved");
    console.log("after promise");
  } else {
    reject(new Error("Promise failed"));
    console.log("after promise");
  }
});

Promise มี 3 สถานะ: pending (เริ่มต้น), resolved (สำเร็จ), rejected (error) Promise pause script execution จนกว่า resolved/rejected แล้วค่อย resume

ใช้ Promise Response

ใช้ then() และ catch() จัดการ response:

promise
  .then(response => {
    console.log(response);
    console.log("after promise");
  })
  .catch(error => {
    console.log(error.message);
    console.log("after promise");
  });

Promises ใช้บ่อยกับ database calls หรือ HTTP requests

Async/Await Functions

async/await เป็นอีกวิธีเขียน logic เดียวกับ Promises แต่ code สั้นกว่า

const firstFunction = () => {
  let resolved = true;
  if (resolved) {
    return { message: "Resolved!" }.message;
  } else {
    return { message: "Error!" }.message;
  }
};

const asyncExample = async () => {
  console.log("Calling function...");
  let result = await firstFunction(); // รอจน firstFunction เสร็จ
  console.log(result);
  return result;
};

asyncExample();

async วางหน้า function keyword (pre-ES6) หรือหน้า parameters (ES6+) await วางหน้า function invocation ที่มี logic - script จะ pause ที่นี่จน function เสร็จ

สรุป

ดูวิธีจำลอง sleep() ของภาษาอื่น: ใช้ setTimeout() แสดง concept ของ async JS เพื่อเข้าใจ Promises และ async/await ซึ่งเป็นวิธีมาตรฐานสำหรับ asynchronous operations ใน JavaScript สมัยใหม่