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

Async/Await Functions ใน JavaScript

Promise object แทนการเสร็จสมบูรณ์ (หรือล้มเหลว) ของ asynchronous operation และค่าที่ได้ Async/await ทำงานบน promises

Async/await ช่วยเขียนโค้ดที่ดูเหมือน synchronous ขณะทำ async tasks ด้านหลัง

เช่น มี async function ที่คืน promise

// Promise that resolves to 100 after 2sec function getHundred() {    return new Promise(resolve => {       setTimeout(() => {          resolve(100);       },    2000);    }); }

ต้องการใช้ในฟังก์ชันแต่ต้องรอค่า ด้วย callbacks ทำได้แบบนี้

function useGetHundred() {    getHundred().then((value) => {       console.log(value);    }) }

แต่ต้องสร้าง callback ไว้รันเมื่อได้ข้อมูล ใช้ async await ลดความซับซ้อนได้

ตัวอย่าง

// Declare an async function. When this function is called, it'll also return a Promise // But inside this function any async calls can be made synchronous using await keyword async function useGetHundredAsync() {    // wait for the getHundred promise to resolve then store its value in value.    let value = await getHundred();    console.log(value) }

ผลลัพธ์

100