dart中的异步

黄鹏宇 392 2021-10-19

关键词 Futures/streams/async/await/then/spawn

1. 异步的用法

1. 用于哪些地方?

  • 从网络中接发数据
  • 向数据库中写入数据.
  • 从文件中读取一些数据

2. 为什么要用异步呢?

一个简单的例子 await
String createOrderMessage () {
  var order = fetchUserOrder();
  return 'Your order is: $order';
}

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

void main () {
  print(createOrderMessage());
}

Your order is: Instance of '_Future'

怎么把他改正确?
Future<String>  createOrderMessage() async {
  var order = await fetchUserOrder();
  return 'Your order is: $order';
}

Future<String>  fetchUserOrder() =>
    Future.delayed(
      Duration(seconds: 2),
      () => 'Large Latte',
    );

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

Fetching user order...

[2秒后]

Your order is: Large Latte

await 告诉系统,等一下它

Future<String>  createOrderMessage() async {
  var a ;
  await fetchUserOrder().then((value){
    a = 'Your order is: $value';
  });  
  return a;
}

Future<String>  fetchUserOrder() =>
    Future.delayed(
      Duration(seconds: 2),
      () => 'Large Latte',
    );

Future<void>  main() async {
  print('Fetching user order...');
  print(await createOrderMessage());
}
  1. 浅探底层实现

image