【Dart】Dart基础知识(三) 同步异步问题 延迟执行

Dart是一门单线程编程语言,所以异步IO+事件循环就显得尤为重要。但在一些业务逻辑上,我们需要手动规定执行顺序。

单函数 延迟执行

  //延迟5秒执行回调函数 
  Future.delayed(new Duration(seconds: 5),(){
    print("eating");
  });
  print("playing")
结果:先执行 playing , 再执行 eating

同步执行+延迟

void main() async{
  //延迟5秒执行回调函数
  await Future.delayed(Duration(seconds: 5),(){
    print("eating");
  });
  print("playing");
}
结果:会在等待5秒后先执行 eating

多个函数延迟加载(同时计算)

  //中括号里的这几个同时在进行,当全部执行完,执行then
  Future.wait([
    Future.delayed(new Duration(seconds: 1), () {
      print("001");
    }),
    Future.delayed(new Duration(milliseconds: 2), () {
      print("002");
    })
  ]).then((List result) => print("over")); //所有运行结果保存在result里

多个函数同步执行(与上一情况对比)

  //多个同步的话 是 每一个都是执行完了再执行下一个
  await Future.delayed(new Duration(seconds: 1), () {
    print("001");
  });
  await Future.delayed(new Duration(milliseconds: 2), () {
    print("002");
  });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值