iT邦幫忙

2022 iThome 鐵人賽

DAY 10
1

async and await

有以下兩點可以區分async和await

  • 要定義非同步函數,請在函數的body之前添加async
  • await只能用在非同步函數裡面
Future<String> createOrderMessage() async {
  var order = await fetchUserOrder();
  return 'Your order is: $order';
}

Future<String> fetchUserOrder() =>
    // Imagine that this function is
    // more complex and slow.
    Future.delayed(
      const Duration(seconds: 2),
      () => 'Large Latte',
    );

Future<void> main() async {
  print('Fetching user order...');
  print(await createOrderMessage());
}

output

Fetching user order...
Your order is: Large Latte

從以上例子我們可以看到async會在函數的body前宣告,接著宣告async的函數裡才能用await
且 createOrderMessage()回傳的type從String變成Future

Execution flow with async and await

在非同步函數body內,第一個await之前的所有同步code都會立即執行

print('Awaiting user order...')在await前面

Future<void> printOrderMessage() async {
  print('Awaiting user order...');
  var order = await fetchUserOrder();
  print('Your order is: $order');
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex and slow.
  return Future.delayed(const Duration(seconds: 4), () => 'Large Latte');
}

void main() async {
  countSeconds(4);
  await printOrderMessage();
}

// You can ignore this function - it's here to visualize delay time in this example.
void countSeconds(int s) {
  for (var i = 1; i <= s; i++) {
    Future.delayed(Duration(seconds: i), () => print(i));
  }
}

output

Awaiting user order...
1
2
3
4
Your order is: Large Latte

改成await在print('Awaiting user order...')前面

將printOrderMessage()修改成以下程式碼

Future<void> printOrderMessage() async {
  var order = await fetchUserOrder();
  print('Awaiting user order...');
  print('Your order is: $order');
}

output

1
2
3
4
Awaiting user order...
Your order is: Large Latte

Awaiting user order...會在await做完後才會執行

參考資料:
https://dart.dev/codelabs/async-await


上一篇
dart&flutter學習之旅-Day09
下一篇
dart&flutter學習之旅-Day11
系列文
dart&flutter學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言