【发布时间】:2021-09-05 22:08:41
【问题描述】:
我正在尝试使用 async await 进行异步编程的 Future。 我测试的代码是一个简单的 Future。
//order a new coffee perhaps!
Future<String> order(String newOrder){
final String Function() func = ()=> "${newOrder} is requested!";
final _order = Future.delayed(Duration(seconds: 5),func);
return _order;
}
当我像承诺一样运行这段代码时。
order("promised order")
.then((result) => print(result))
.catchError((err){
print(err.error);
});
这表现得像一个异步非阻塞代码
但是,当我使用 async/await 运行相同的代码时,它的行为类似于同步代码并阻塞所有其他代码,它会等待 5 秒才能运行下一行。
void main(List<String> arguments) async {
final _myOrder = await order('Lattee mocha');
print(_myOrder);
//...all the other code waits for
}
所以我认为 async/await 与未阻塞的期货相同。 怎么会阻塞其他代码执行?
【问题讨论】:
-
await没有阻塞。什么代码在等待 5 秒才能执行?在 Promise 示例中,print(result)何时运行?在await示例中,await之后的所有内容都是延续的一部分,并将在await完成后运行
标签: dart async-await