【问题标题】:Understanding asynchronous and synchronous in Dart理解 Dart 中的异步和同步
【发布时间】:2021-05-15 08:46:17
【问题描述】:

我们知道,在 Dart 中,一切都是同步运行的,并且根据我在互联网上找到的一些定义

当您同步执行某事时,您会等待它完成,然后再继续执行另一项任务。当您异步执行某项操作时,您可以在它完成之前继续执行另一个任务。

我在这里不明白的是为什么在 c 之前打印 b 我的意思是如果代码同步运行,那么它应该等待第 2 行完成打印c 并且仅在打印 c 之后 它应该打印 b

Ps- 我知道我可以使用 async 和 await 关键字来等待第 2 行完成它的执行。我只是想了解这个同步代码是如何工作的。

void main(){

   print("a");

   Future.delayed(Duration(seconds: 
   5),(){
    print("c");
  });
   print("b");
}

Output- a
        b
        c
       

【问题讨论】:

    标签: flutter dart asynchronous async-await synchronous


    【解决方案1】:

    当你写的时候:

    print("a");
    
    Future.delayed(Duration(seconds: 5),(){
        print("c");
    });
    print("b");
    

    您告诉程序打印“a”,然后启动Future,它将在 5 秒内解析并打印“c”,然后打印“b”;但你永远不会告诉程序等待Future 完成。

    这是同步的。

    这就是为什么您必须使用await 关键字让程序等待Future 完成后才能移动到下一条指令。

    【讨论】:

    • 解释得很好!
    【解决方案2】:

    不,不是。如果您使用await 关键字,它只会在b 之前打印c。这个关键字告诉 Dart 等到这个未来完成,然后继续下一个任务。

    例如

    void main() async {
    
       print("a");
    //await tells dart to wait till this completes. If it's not used before a future, then dart doesn't wait till the future is completed and executes the next tasks/code.
    await Future.delayed(Duration(seconds: 
       5),(){
        print("c");
      });
       print("b");
    }
    

    输出

    Output- a
            c
            b
           
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-01
      • 2021-10-04
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多