1. 程式人生 > 其它 >認識 Dart 非同步程式設計 async/await 關鍵字(二)

認識 Dart 非同步程式設計 async/await 關鍵字(二)

認識 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關鍵字即可。