下面这段代码的输出是什么?

import 'dart:async';
main() {
  print('main #1 of 2');
  scheduleMicrotask(() => print('microtask #1 of 2'));
 
  new Future.delayed(new Duration(seconds:1),
                     () => print('future #1 (delayed)'));
  new Future(() => print('future #2 of 3'));
  new Future(() => print('future #3 of 3'));
 
  scheduleMicrotask(() => print('microtask #2 of 2'));
 
  print('main #2 of 2');
}

 答案在下面:

1 main #1 of 2
2 main #2 of 2
3 microtask #1 of 2
4 microtask #2 of 2
5 future #2 of 3
6 future #3 of 3
7 future #1 (delayed)

main方法中的普通代码都是同步执行的,所以肯定是main打印先全部打印出来,等main方法结束后会开始检查microtask中是否有任务,若有则执行,执行完继续检查microtask,直到microtask列队为空。所以接着打印的应该是microtask的打印。最后会去执行event队列(future)。由于有一个使用的delay方法,所以它的打印应该是在最后的。

原文:https://blog.csdn.net/meiyulong518/article/details/81773365 

 

相关文章:

  • 2021-04-02
  • 2022-01-21
  • 2021-07-03
  • 2021-11-29
  • 2022-02-12
  • 2021-06-13
  • 2022-01-03
猜你喜欢
  • 2022-12-23
  • 2021-08-07
  • 2022-12-23
  • 2022-12-23
  • 2021-07-10
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案