Node 7 ออกแล้วนะครับ ตอนนี้รองรับ Es6 features ถึง 98% แล้ว ที่นักพัฒนาดูจะให้ความสนใจกันเป็นพิเศษคือสามารถใช้งาน async/await ซึ่งเป็น synctax ของ Es7 ได้โดยไม่ต้องติดตั้งตัว transpile อย่าง Babel เพิ่มเติม
แต่ …. ยังไม่ได้เปิดใช้งานเป็นค่า default ถ้าอยากใช้ async/await ต้องใส่ option –harmony-async-await ตอนรัน
node --harmony-async-await server.js
การใช้งาน async ทำได้โดยการใส่ keyword async หน้า function ที่เราต้องการ function ซึ่งจะทำให้ function นั้น return promise object สามารถใช้ then/catch แบบ promise chain ได้เลย ยกตัวอย่างเช่น
async function fetchUrl(url) { return request.get(url).end() } fetchUrl('https://api.mydomain.com/v1/user').then(data => { // do something })
กล่าวโดยสรุป async ทำให้ใช้งาน promise ได้ง่ายขึ้นนั่นเอง เพราะไม่ต้อง new Promise((resolve, reject) => {}) มาครอบ ได้ผลลัพธ์ก็ resolve ถ้า error ก็ reject เหมือนเดิมแล้ว
ส่วน await ถ้าใครเคยใช้ generator มาก่อนคงจะคุ้นเคยกับ keyword yield ซึ่งเป็นการ resolve async function จนกว่าจะได้ผลลัพธ์ จึงจะทำงานต่อซึ่งทำให้การเขียนโปรแกรมทำงานแบบ procedural เหมือนภาษาโปรแกรมทั่วไป เช่น
async function fetchUrl(url) { return request.get(url).end() } function toUpper(str) { return str.toUpperCase() } async function formatUrlContent(url) { const content = await fetchUrl(url) return toUpper(content.body) } formatUrlContent('https://api.mydomain.com/v1/user').then(data => { // display UPPER case of content })
จากตัวอย่างโค้ดข้างบน มีข้อควรระวังการใช้งานคือ await ต้องใช้งานกับ function ที่มี async อยู่เท่านั้น ใช้ลอยๆ โดดๆ ไม่ได้ครับ
การใช้ async/await โดยส่วนตัวผมคิดว่าทำให้ JavaScript แบบ Es6 ไม่รกรุงรังเหมือนแต่ก่อน โค้ดสวยขึ้นเยอะเลยทีเดียว