理解 Dart 中的异步和同步

Understanding asynchronous and synchronous in Dart

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

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

这里我不明白的是为什么 b 打印在 c 之前 我的意思是如果代码是 运行同步然后它应该等待第 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
       

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

例如

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
       

当你写:

print("a");

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

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

这是同步的。

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