認識 Dart 非同步程式設計 async/await 關鍵字(二)
阿新 • • 發佈:2022-03-23
在認識 Dart 非同步程式設計(一)中,我們初步認識了 Dart 非同步程式設計,以及代表非同步操作結果的Future
物件。
如果非同步任務過多,超過三個以上,在程式碼層面上,造成多層“倒三角”,使閱讀性大大降低。
getHobbies() { post('http://api.example.com/get/user/${userId}').then((user) { post('http://api.example.com/get/tags/${user.id}').then((tags) { post('http://api.example.com/get/hobbies/${user.id}').then((hobbies) { print(hobbies); }); }); }); }
async/await
關鍵可以解決上訴“倒三角”現象,並使程式碼的閱讀性大大提高,也利於程式碼的書寫。
getHobbies() async {
User user = await post('http://api.example.com/get/user/${userId}');
Tags tags await post('http://api.example.com/get/tags/${user.id}');
Hobbies hobbies = await post('http://api.example.com/get/hobbies/${user.id}');
print(hobbies);
}
async
await
用在阻塞任務前,例如,獲取使用者是一個網路請求,且此任務會發生一個等待,那麼在前面新增上await
關鍵字即可。