1. Async await là gì
- Hàm async luôn trả về 1 Promise
- Await chính là promise.then(res=>...). Kết quả của await chính là res của then trong promise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> async function async1() { console.log("async1 start") // 2 await async2(); console.log("async1 end") // 6 } async function async2() { console.log("async2"); // 3 return 5 } console.log("script start") //.start setTimeout(function () { console.log("setTimeout") //.end }, 0); async1(); new Promise(function (resolve) { console.log("promise1"); // 4 resolve(); }).then(function () { console.log("promise2"); // 7 }) console.log("script end") // 5 </script> </body> </html> |
Demo sử dụng Asyn await để Get Data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <h2>Xử lý bất đồng bộ trong ES6</h2> <script> async function getFakeData() { try { let url = 'https://fakestoreapi.com/users?limit=5'; let response = await fetch(url); let responseJSON = await response.json(); console.log(responseJSON); } catch (error) { console.log('Failed to fetch data. ', error.message); } } let example = getFakeData(); console.log(example); </script> </body> </html> |